lundi 2 octobre 2017

Set Event-Handler by reflection with Type and Template argument

I would like to set an event handler only by reflection, I can get all the types but I can't achieve it.

public delegate void MyHandler<T>(IMyInterface<T> pParam);    
public interface IMyInterface<T> 
{
    MyHandler<T> EventFired { get; set; }
}

void myFunction()
{
    //admit vMyObject is IMyInterface<ClassA>
    var vMyObject = vObj as IMyInterface<ClassA>;
    //get the generic type => ClassA
    var vTypeGeneric = vTypeReturn.GenericTypeArguments.FirstOrDefault();
    //build the type handler for the event MyHandler<ClassA>
    Type vAsyncOP = typeof(MyHandler<>).MakeGenericType(vTypeGeneric);

    // here I don't know how to create the Event handler to set EventFired 
    // dynamically with the code inside 

    var vEventFired = vMyObject.GetType().GetProperty("EventFired");
    vEventFired.SetMethod etc...

}

I found some code with the usage of Lambda/Expression but I don't understand how to use it in this case.





Aucun commentaire:

Enregistrer un commentaire