Is it possible to target EventHandler in a lambda expression?

For a simple example, if I had some type of UI buttons, I could write a function that takes an expression that points to its event handler Click:

SomeMethod<SomeButtonClass>(button => button.Click);

I am trying to eliminate some of the magic strings that are currently used for the system to spice things up. The code in question is derived from a message from Frank Krueger (worth reading if you need some kind of background).

public static Task<TEventArgs> GetEventAsync<TEventArgs>(this object eventSource, string eventName) where TEventArgs : EventArgs {
    //...
    Type type = eventSource.GetType();
    EventInfo ev = type.GetEvent(eventName);
    //...
}

While the features inside are probably not important, the full method allows you to use startup Eventas a source of completion for Task, which simplifies management with await. For some class that triggers an event, you can associate it with Taskbased on that event with a simple call.

Task<EventArgs> eventTask = someEventCausingObject.GetEventAsync<EventArgs>("SomeEventHandler");
// traditionally used as someEventCausingObject.SomeEventHandler += ...;
await eventTask;
// Proceed back here when SomeEventHandler event is raised.

I use it with pleasure for several projects, but it has its drawbacks, one of the biggest of which is the use of a hard-coded event name strings. This leads to the fact that changes to the name of the event become exceptions at run time, and determining the use of the event is difficult.

I started trying to make a version that would EventHandlerbe allowed to be transferred as part Expressionwith the goal of something like this:

await someEventCausingObject.GetEventAsync<EventCausingClass, EventArgs>(x => x.SomeEventHandler);

... ...

public static Task<TEventArgs> GetEventAsync<TSource, TEventArgs>(this TSource eventSource, Expression<Func<TSource, EventHandler>> eventHandlerExpression) where TEventArgs : EventArgs {
    //...
}

, lambda :

Error CS0070: The event `SomeEventHandler' can only appear on the left hand side of += or -= when used outside of the type `EventCausingClass'.

, , , , , . , "" " ", , , - += . , - .

+3
1

, . , #, add_EventName remove_EventName.

, # - http://msdn.microsoft.com/en-us/library/z47a7kdw.aspx

SO , NO - Jon Skeet fooobar.com/questions/749857/...

, -

private static void Subscribe(Action addHandler)
{
    var IL = addHandler.Method.GetMethodBody().GetILAsByteArray();

    // Magic here, in which we understand ClassName and EventName
    ???
}

,

Subscribe(() => new Button().Click += null);

Cecil http://www.mono-project.com/Cecil IL , .

, , ( ) ( Subscribe ). , .

+1

All Articles