jeudi 27 octobre 2016

How can I programmatically retrieve an EventInfo for an event without hard coding its name?

Given an interface:

IEventProvider
{
    event EventHandler<string> StringAvailable;

    void RequestString();
}

I want to retrieve an EventInfo for StringAvailable through some method that can be called like this: EventInfo ei = GetEventInfo(providerInstance.StringAvailable) or something to that effect. I don't want to have to pass a string containing its name.

I've tried to abuse lambdas and expression trees to extract the name of the event being passed in but to no avail. Because events are not first class members in C# this is proving to be difficult. I just help finding a way to get the name of the event at run-time with code that can be statically validated by the compiler to ensure the event exists at compile time.

My workaround right now is to remove all of the events from the classes I want to work with and change them to Action<T>. This is less than ideal though.

For those of you wondering why I'm doing this, I want to allow classes that use the event based asynchronous pattern to be adapted to async/await automatically at run-time using IL generation. In my example interface above, the adapter would wrap RequestString and StringAvailable and expose public async Task<string> RequestStringAsync() using DynamicMethod.





Aucun commentaire:

Enregistrer un commentaire