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

后端 未结 5 1025
佛祖请我去吃肉
佛祖请我去吃肉 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:41

    You can use an anonymous method instead:

    Event += (sender, e) =>
    {
         // Multiple lines
         // of code here
    };
    
    0 讨论(0)
  • 2020-12-25 12:46

    Lambdas are implicitly convertible to delegate types with the right shape, but two same-shaped delegate types are not implicitly convertible to one another. Just make the local variable have type EventHandler instead.

    EventHandler h = (o, ea) => { ... };
    e += h;
    ...
    e -= h;
    

    (in case it helps:

    Action<object, EventArgs> a = (o, ea) => { }; 
    EventHandler e = a;  // not allowed
    EventHandler e2 = (o,ea) => a(o,ea);  // ok
    

    )

    0 讨论(0)
  • 2020-12-25 12:49

    Declare your event as

    public event Action<object, EventArgs> e;
    

    Then you can directly add your action:

    Action<object, EventArgs> a = something;
    e += a;
    
    0 讨论(0)
  • 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<T1, T2>
    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] */ };
      
    0 讨论(0)
  • 2020-12-25 12:56
    Action<Object, EventArgs> a = (o, ea) => { };
    EventHandler e = a.Invoke;
    
    0 讨论(0)
提交回复
热议问题