One shot events using Lambda in C#

前端 未结 8 1627
無奈伤痛
無奈伤痛 2021-01-31 07:55

I find myself doing this sort of thing quite often:-

 EventHandler eh = null;  //can\'t assign lambda directly since it uses eh
 eh = (s, args) =>
 {
     //s         


        
8条回答
  •  鱼传尺愫
    2021-01-31 08:28

    Does it work? If so, then I say go for it. For a one-shot event that looks to be quite elegant.

    What I like...

    • If s is garbage collected, so will the event handler.
    • The detaching code is right next to the attaching code, making it easy to see what you are are doing.

    You might be able to generalize it, but I'm not entierly sure how to because I can't seem to get a pointer to a event.

提交回复
热议问题