我在这个 SO 回答之后对我的 C# 4.0 事件处理程序逻辑进行建模并得到错误
ThresholdExceededEvent 只能出现在 += 或 -= 的左侧
代码
private EventHandler<EventLogAlert> thresholdExceededEventDelegate;
public event EventHandler<EventLogAlert> ThresholdExceededEvent
{
add { thresholdExceededEventDelegate += value; Console.WriteLine("add operation"); }
remove { thresholdExceededEventDelegate -= value; Console.WriteLine("remove operation"); }
}
protected virtual void OnThresholdExceededEvent(EventLogAlert e)
{
EventHandler<EventLogAlert> handler = ThresholdExceededEvent;
if (handler != null)
{
handler(this, e);
}
}
但是当我这样做时它会编译....
public event EventHandler<EventLogAlert> ThresholdExceededEvent;
protected virtual void OnThresholdExceededEvent(EventLogAlert e)
{
EventHandler<EventLogAlert> handler = ThresholdExceededEvent;
if (handler != null)
{
handler(this, e);
}
}
首选方法是什么?