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

你。 提交于 2019-11-30 12:30:46

问题


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 use to remove the event) so i set up an Action<object, EventArgs> variable and moved the lambda there. The main error was that it could not convert an Action<object, EventArgs> to an EventHandler. I thought lambda expressions were implicitly convertable to event handlers, why doesn't this work?


回答1:


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

)




回答2:


Action<Object, EventArgs> a = (o, ea) => { };
EventHandler e = a.Invoke;



回答3:


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] */ };
    



回答4:


Declare your event as

public event Action<object, EventArgs> e;

Then you can directly add your action:

Action<object, EventArgs> a = something;
e += a;



回答5:


You can use an anonymous method instead:

Event += (sender, e) =>
{
     // Multiple lines
     // of code here
};


来源:https://stackoverflow.com/questions/1551953/actionobject-eventargs-could-not-be-casted-to-eventhandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!