我正在尝试理解以下所有选项是否可行。我完全理解委托和事件的使用,但是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}
}
event
关键字。如果不这样做,单个消费者可以清除所有其他订阅者(如果他们想要的话)。这里 有一个关于Action
和EventHandler
的问题。 - JonesopolisAction
称为语法糖,它只是一种类型,但它确实节省了一些输入。而且使用Action
和Func
时,你很少需要声明委托类型。 - Brian Rasmussen