Action<object, EventArgs> could not be cast to EventHandler?

后端 未结 5 1045
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-25 12:24

I was wiring up an event to use a lambda which needed to remove itself after triggering. I couldn\'t do it by inlining the lambda to the += event (no accessable variable to

5条回答
  •  盖世英雄少女心
    2020-12-25 12:50

    In general, delegates can't be cast because they have no inheritance tree defining which casts are valid. To that end, you have two choices:

    1. Use a variable of type EventHandler instead of the Action
    2. Use an inline declaration.

      // option 1: local variable
      EventHandler eh = (o, ea) => { /* [snip] */ };
      obj.event += eh;
      obj.event -= eh;
      
      // option 2: inline declaration
      obj.event += (o, ea) => { /* [snip] */ };
      

提交回复
热议问题