2
我想了解下面的所有選項是否可行。我完全理解委託和事件的用法,但Action似乎通過使句法更容易(或者我錯過了某些東西)來提供語法糖? 我測試了所有這些,他們的工作,但這並不意味着他們都是好模式。活動,代表與行動<T>
public delegate WorkCompleteDel(sting value);
public class MyClass{
//Are these all viable, safe options?
//ties the above delegate, pretty standard pattern
public event WorkCompleteDel WorkCompletedDelEvent;
//OR
//this seems to be the easiest but only supports
//on listner/subscriber. IF thats all you need, seems
//reasonble?
public Action<string> WorkCompleteHandler1 {get; set;}
//OR
//this is similar to the one below it but
//uses an action. Not sure if using he event keyword
//now gives me the ability to have multple subscibers
//(but I think it does due to multicast delegate class)
public event Action<string> WorkCompleteHandler1;
//OR
//another standard patthen
public event EventHandler<MyEventHandlerArgs> WorkCompleteHandler2
}
public class MyEventHandlerArgs: EventArgs
{
public string MyString {get; set}
}
使用'event'關鍵字很重要。如果你不這樣做,一個消費者可以消滅所有其他用戶,如果他們想要的話。 [這裏](http://stackoverflow.com/questions/1431359/event-action-vs-event-eventhandler)是一個關於'動作'vs'EventHandler'的問題 – Jonesopolis
我不會叫'動作'語法糖 - 它只是一種類型,但它確實爲您節省了一些鍵入操作,並且使用'Action'和'Func'您很少需要聲明委託類型。 –
Thanks..so如果我瞭解它,如果您完全控制消費者的時間和數量(如簡單桌面應用程序),則可以排除event關鍵字。但是,它並不是一個可接受的模式。 –