【发布时间】:2021-01-01 17:07:52
【问题描述】:
我正在阅读有关 EventHandlers 的 .NET 文档,但不理解来自 https://docs.microsoft.com/en-us/dotnet/standard/events/ 的这段代码:
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
}
局部变量handler的作用是什么?为什么不直接调用 TresholdReached TresholdReached?.Invoke(this, e); 呢?
类似的例子在这里:
https://docs.microsoft.com/en-us/dotnet/api/system.eventhandler-1?view=net-5.0
【问题讨论】:
-
局部变量
handler的作用是什么,无在这种情况下,只是一个简短的例子来说明@987654328 @ 对象是强类型的。我认为编译器无论如何都会摆脱局部变量。