Is this a better way to fire/invoke events without a null check in C#?

后端 未结 4 718
庸人自扰
庸人自扰 2021-02-05 19:05

Most code I have seen uses the following way to declare and invoke event firing:

public class MyExample
{
    public event Action MyEvent; // could be an event E         


        
4条回答
  •  再見小時候
    2021-02-05 19:31

    It can still be null. Consider:

        var x = new MyExample();
        x.MyEvent += SomeHandler;
    
        // ... later, when the above code is disposed of
    
        x.MyEvent -= SomeHandler;
    

    EDIT: actually, I take it back. Having tested this, if you've used an anonymous delegate to set the handler, it doesn't look like you can clear it, so you can save the null check.

    I'm not sure whether this is reliable behaviour though, or just an artifact of the language implementation...

提交回复
热议问题