Should I instantiate a new delegate or not?

前端 未结 2 841
既然无缘
既然无缘 2020-12-17 01:38

I just realized I can add an event handler in two ways:

Consider an event handler like so:

private void MyEventHandler()
{}

Method

相关标签:
2条回答
  • 2020-12-17 02:12

    I believe that while you can unsubscribe from the second, you'd not be able to unsubscribe from the first.

    That would be a pretty important distinction. There is really nothing to be gained by wrapping it in an Action in any case.

    update

    Okay, I think I misunderstood what you were doing. If the event is declared as

    public event Action MyEvent;
    

    then the two subscriptions are equivalent, the second being shorthand for the first.

    There are actually other ways to add event handlers:

    MyObject.MyEvent += delegate { MyEventHandler(); };
    
    MyObject.MyEvent += () => MyEventHandler();
    

    In these cases, you would not be able to unsubscribe. In these examples, the delegates are calling the handler method, but usually when employing this method it is to avoid having to create separate handler methods -- the handler code goes right in the anonymous method.

    0 讨论(0)
  • 2020-12-17 02:21

    There is no difference, the generated IL is the same. The shorter form was introduced in .net/c# 2.0 as a convenience function, although Visual Studio still does the first form on Tab Completion.

    See this question for some more info.

    0 讨论(0)
提交回复
热议问题