我想創建一個流利的擴展方法來訂閱(並且不太重要的是取消訂閱)事件。這是地方的+= new Eventhandler(Method)
訂閱/取消訂閱(添加/刪除)到擴展方法內部的事件
與使用.RespondBy(Method)
延長我想這樣做:object.WhenSomethingChanges.RespondBy(DoingThisOtherThing);
取而代之的是:object.WhenSomethingChanges += new EventHandler(DoingThisOtherThing);
我做了一堆google搜索的,雖然我沒有完全掌握複雜的細節,我現在明白,這與你是否訪問本地領域或公共事件有關。
就這樣說,我只是在關注「如何」這可以做,而不關心「爲什麼」我的第一次嘗試沒有奏效。如果不解決方法,至少一個明確的 「你不能做到這一點......在所有的,直到永遠。」 也將是有用的信息...
CommuncationsStatusPresenter (Image)
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;
}
}
}
RespondBy
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;
}
ICommunicationsModel
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; }
}
}
那麼,這似乎足夠明確!謝謝:) – HodlDwon
嗯...這看起來很有希望,儘管潛在更多的努力比收益http://stackoverflow.com/questions/18385967/c-sharp-event-keyword-advantages基本上這個想法是短路標準的'事件'關鍵字修飾符,並手動通過代理/操作自由地高興。我沒有嘗試過實現這個,鏈接中沒有例子,但所有的部分似乎都在那裏,使我的原始問題有一個可能的(雖然不是推薦)的解決方案。我會在某個時候重新審視這個問題,看看我是否可以得到一個優雅的實現,即使它只是踢。 – HodlDwon