为什么在本Microsoft文档中声明了额外的EventHandler



events上的Microsoft文档包括以下示例:

class Counter
{
public event EventHandler ThresholdReached;
protected virtual void OnThresholdReached(EventArgs e)
{
EventHandler handler = ThresholdReached; // <-- (*)
handler?.Invoke(this, e);
}
// provide remaining implementation for the class
}

你可以在这里找到它:https://learn.microsoft.com/en-us/dotnet/standard/events/

(*)实例化背后的动机是什么,为什么不写:

class Counter
{
public event EventHandler ThresholdReached;
protected virtual void OnThresholdReached(EventArgs e)
{
ThresholdReached?.Invoke(this, e);
}
}

没有区别。也许作者想证明您可以为变量分配事件处理程序,但您可以像您建议的那样缩短代码,而不会产生任何后果。

最新更新