gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:01:02 24 4
gpt4 key购买 nike

我正在尝试了解以下所有选项是否可行。我完全理解委托(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com