简体   繁体   English

为什么使用匿名委托声明此事件?

[英]Why is this event declared with an anonymous delegate?

I have seen people define their events like this: 我见过人们定义他们的事件是这样的:

public event EventHandler<EventArgs> MyEvent = delegate{};

Can somebody explain how this is different from defining it without it? 有人可以解释一下如果没有它,这与定义它有何不同? Is it to avoid checking for null when raising the event? 是否要在提升事件时避免检查null?

You got it - adding the empty delegate lets you avoid this: 你明白了 - 添加空委托让你避免这种情况:

public void DoSomething() { 
    if (MyEvent != null) // Unnecessary! 
        MyEvent(this, "foo"); 
} 

此声明确保MyEvent永远不为null,从而消除了每次都必须检查null的繁琐且容易出错的任务,每次触发事件时都要执行额外的空委托。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM