c# - 事件、委托(delegate)与 Action<T>

标签 c# .net events delegates

我正在尝试了解以下所有选项是否可行。我完全理解委托(delegate)和事件的用法,但 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}

}

最佳答案

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

event关键字具有特殊含义。它防止此委托(delegate)在类外被触发。参见 this excellent answer讨论为什么 event很重要,什么时候会用到(或不用)。

关于c# - 事件、委托(delegate)与 Action<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32279608/

相关文章:

c# - 在代码中配置 WCF 服务绑定(bind)

c# - 从 SHELLEXECUTEINFO 获取类名

c# - 将常见的异常抛出逻辑提取到自己的方法中是一种好习惯吗?

javascript - 如何防止其他点击事件在其中一个已在 jQuery 中运行时运行?

c# - EventArgs 作为事件模式中的基类的目的是什么?

c# - 将事件处理程序作为方法参数传递

c# - 同一解决方案中的 ASP.NET 多个项目

c# - 使用 GZipStream 压缩

c# - LiveLoginResult.Status 未知?

objective-c - 让我的 Cocoa 应用程序响应键盘播放/暂停键?