Compiler complains when Event has add & remove properties. Compiles OK without

白昼怎懂夜的黑 提交于 2019-12-13 04:48:23

问题


I'm modeling my C# 4.0 event handler logic after this SO answer and get the error

ThresholdExceededEvent can only appear on the left hand side of += or -=

Code

    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);
        }
    }

but it compiles when I do this....

   public event EventHandler<EventLogAlert> ThresholdExceededEvent;
    protected virtual void OnThresholdExceededEvent(EventLogAlert e)
    {
        EventHandler<EventLogAlert> handler = ThresholdExceededEvent;
        if (handler != null)
        {
            handler(this, e);
        }
    }

What is the preferred approach?


回答1:


Instead of

EventHandler<EventLogAlert> handler = ThresholdExceededEvent;

Use

EventHandler<EventLogAlert> handler = thresholdExceededEventDelegate;



回答2:


Use the second approach; if you don't need custom handling of attaching to and detaching from the event (and you aren't trying to implement an interface's event explicitly), then there's no need for the more verbose syntax of the first option; the code in the second will compile down to something very closely resembling the second option, anyway.

The syntax error in your first block of code is that you're trying to execute an explicitly-implemented event directly. You'll need to execute the delegate itself rather than the event in that case.



来源:https://stackoverflow.com/questions/10593632/compiler-complains-when-event-has-add-remove-properties-compiles-ok-without

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!