我想创建一个流畅的扩展方法来订阅(不太重要的是取消订阅)一个事件。那是使用.RespondBy(Method)
代替 a的扩展+= new Eventhandler(Method)
我想做这个:object.WhenSomethingChanges.RespondBy(DoingThisOtherThing);
而不是这个:object.WhenSomethingChanges += new EventHandler(DoingThisOtherThing);
我做了一堆谷歌搜索,虽然我没有完全掌握错综复杂的细节,但我现在明白这与你是访问本地领域还是公共活动有关。
话虽如此,我只是对“如何”做到这一点感兴趣,而不关心“为什么”我的第一次尝试没有奏效。解决方法失败,至少是一个明确的“你不能这样做......永远。 ”也将是有用的信息......
CommuncationsStatusPresenter(代码)
using System;
using InspectionStation.Models;
using InspectionStation.Views;
using MachineControl.OPC;
namespace InspectionStation.Presenters
{
public class CommuncationsStatusPresenter
{
// Fields
private ICommunicationsModel m_model;
private ICommunicationsView m_view;
// Constructor
public CommuncationsStatusPresenter
(ICommunicationsModel p_model, ICommunicationsView p_view)
{
m_model = p_model;
m_view = p_view;
HookEvents();
}
private void HookEvents()
{
m_model
.When_Communications_Pulses_Heartbeat
.RespondBy(Setting_the_state_of_an_Indicator);
}
// Eventhandler
void Setting_the_state_of_an_Indicator(Tag sender, EventArgs e)
{
bool State = sender.BooleanValue;
m_view.Set_Communications_Status_Indicator = State;
}
}
}
响应者
using System;
namespace Common.Extensions
{
public static partial class ExtensionMethods
{
public static
void RespondBy<TSender, TEventArgs>(this
GenericEventHandler<TSender, TEventArgs> p_event,
GenericEventHandler<TSender, TEventArgs> p_handler
) where TEventArgs : EventArgs
{
p_event += new GenericEventHandler<TSender, TEventArgs>(p_handler);
}
}
}
using System;
namespace Common
{
[SerializableAttribute]
public delegate void GenericEventHandler<TSender, TEventArgs>
(TSender sender, TEventArgs e)
where TEventArgs : EventArgs;
}
通信模型
using System;
using Common;
using MachineControl.OPC;
namespace InspectionStation.Models
{
public interface ICommunicationsModel
{
event GenericEventHandler<Tag, EventArgs>
When_Communications_Pulses_Heartbeat;
}
}
ICommunicationsView
namespace InspectionStation.Views
{
public interface ICommunicationsView
{
bool Set_Communications_Status_Indicator { set; }
}
}