Difference between wiring events using “new EventHandler” and not using new EventHandler"?

后端 未结 4 858
情书的邮戳
情书的邮戳 2021-01-18 10:06

What\'s the difference between the two?

object.ProgressChanged += new EventHandler(object_ProgressChanged)

object.ProgressCh         


        
4条回答
  •  耶瑟儿~
    2021-01-18 11:01

    Basically, one is shorter than the other. It's just synctactic sugar.

    The "correct" syntax is the first one, as ProgresChanged is an EventHandler event, so for you to assign a actual handler to it, you need to create a new EventHandler object, whose constructor takes as a parameter the name of a method with the required signature.

    However, if you just specify the name of the method (second syntax), an instance of the eventHandler class is created implicitly, and that instance is assigned to the ProgressChanged event.

    I prefer using the second method because it's shorter, and does not lose any information. There are not much contexts where you could mistake a += methodName construct for something else.

提交回复
热议问题