分配给空委托的事件声明 [英] Event declaration with assignment to empty delegate
问题描述
我对经常在网上偶然发现的一段代码有疑问。例如,
I have question on a piece of code I often stumble across online. For example
public static event Action<Foo> foo = delegate{ };
我在声明的左侧。但是右手边令人困惑。将事件分配给带有空括号的委托人有什么意义?
I got the left hand side of the declaration. But the right hand side is confusing. What is the point in assigning the event to a delegate with empty parenthesis?
推荐答案
更新:在现代版本的C#中,推荐使用的模式是将其保留为null并使用<$ c 运算符:
UPDATE: in modern versions of C#, the recommended pattern to use is to leave it as null and use the ?.
operator:
event Action<Foo> foo; // leave it as null as the default
// ...
foo?.(new Foo());
在较旧版本的C#中,其原因是模式可能是 event
字段的默认值为 null
。这要求您每次想引发事件时都使用null检查-在未初始化的事件$ c上调用
foo()
$ c>字段将导致 NullReferenceException
。只需给它一个合理的默认值(如无操作),便更加方便,这样您就可以直接引发事件,而无需使用包装方法或其他任何方法。
In older versions of C#, the reason for this pattern could be that the default value of an event
field is null
. This requires the use of a null-check every-time you want to raise the event - calling foo()
on an uninitialised event
field would result in a NullReferenceException
. It's more convenient to just give it a sensible default value like a no-op, that way you can raise the event directly without having to use a wrapper method or anything.
这篇关于分配给空委托的事件声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!