事件、委托与操作<T>

Bob*_*ach 2 .net c# events delegates

我试图了解以下所有选项是否可行。我完全理解委托和事件的用法,但 Action 似乎通过使它更容易(或者我错过了什么)来提供语法糖?我已经测试了所有这些并且它们有效,但这并不意味着它们都是好的模式。

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}

}
Run Code Online (Sandbox Code Playgroud)

dss*_*539 6

Action<T>只是一种使用委托的简单通用方法。它相当于delegate MyDelegate(T arg) 添加它是为了节省您的一些输入,并且在尝试弄清楚您的委托用作参数时,它确实为读者节省了很多麻烦。

event关键字具有特殊的意义。它可以防止在类外触发此委托。有关为什么重要以及何时使用(或不使用)的讨论,请参阅此优秀答案event