gpt4 book ai didi

C# 事件和 Lambdas,空检查的替代方法?

转载 作者:太空狗 更新时间:2023-10-29 22:55:44 25 4
gpt4 key购买 nike

有人看到任何缺点吗?应该注意的是,您不能从事件委托(delegate)列表中删除匿名方法,我知道这一点(实际上这是概念上的动机)。

这里的目标是替代:

if (onFoo != null) onFoo.Invoke(this, null);

还有代码:

public delegate void FooDelegate(object sender, EventArgs e);

public class EventTest
{
public EventTest()
{
onFoo += (p,q) => { };
}

public FireFoo()
{
onFoo.Invoke(this, null);
}

public event FooDelegate onFoo;

最佳答案

一种替代方法是创建一个扩展方法:

public static class EventExtensions {
public static void Fire<T>(this EventHandler<EventArgs<T>> handler, object sender, T args) {
if (handler != null)
handler(sender, new EventArgs<T>(args));
}
}

现在只是:

TimeExpired.Fire(this, new EventArgs());

关于C# 事件和 Lambdas,空检查的替代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2877809/

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