Raising C# events with an extension method - is it bad?

后端 未结 6 1246
执念已碎
执念已碎 2020-12-02 10:55

We\'re all familiar with the horror that is C# event declaration. To ensure thread-safety, the standard is to write something like this:

public event EventH         


        
6条回答
  •  隐瞒了意图╮
    2020-12-02 11:47

    It will still work with events that have an explicit add/remove - you just need to use the delegate variable (or however you've stored the delegate) instead of the event name.

    However, there's an easier way to make it thread-safe - initialize it with a no-op handler:

    public event EventHandler SomethingHappened = delegate {};
    

    The performance hit of calling an extra delegate will be negligible, and it sure makes the code easier.

    By the way, in your extension method you don't need an extra local variable - you could just do:

    static public void RaiseEvent(this EventHandler @event, object sender, EventArgs e)
    {
        if (@event != null)
            @event(sender, e);
    }
    
    static public void RaiseEvent(this EventHandler @event, object sender, T e)
        where T : EventArgs
    {
        if (@event != null)
            @event(sender, e);
    }
    

    Personally I wouldn't use a keyword as a parameter name, but it doesn't really change the calling side at all, so do what you want :)

    EDIT: As for the "OnXXX" method: are you planning on your classes being derived from? In my view, most classes should be sealed. If you do, do you want those derived classes to be able to raise the event? If the answer to either of these questions is "no" then don't bother. If the answer to both is "yes" then do :)

提交回复
热议问题