How to pass parameters to a method by reflection

2019-08-23 12:34发布

问题:

Further to my precedent question, I want to pass parameters to the method "WriteTrace". But I don't know how to do this.

Here the actual code :

public class Trace
{
    public void WriteTrace(object sender, EventArgs e)
    {
        Console.WriteLine("Trace !");
    }
}



public void SubscribeEvent(Control control)
{
    if (typeof(Control).IsAssignableFrom(control.GetType()))
    {
        Trace test = this;
        MethodInfo method = typeof(Trace).GetMethod("WriteTrace");

        EventInfo eventInfo = control.GetType().GetEvent("Load");

        // Create the delegate on the test class because that's where the
        // method is. This corresponds with `new EventHandler(test.WriteTrace)`.
        Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method);
        // Assign the eventhandler. This corresponds with `control.Load += ...`.
        eventInfo.AddEventHandler(control, handler);
    }
}

Now I want to get some infos in the trace :

  • The name of the control
  • The name of the event

    public void WriteTrace(object sender, EventArgs e)
    {
        Console.WriteLine("Control : " + e.ControlName + "Event : " + e.EventName);
    }
    

Do I create a class TraceEventArgs which derives from EventArgs with these infos ? How to pass these infos in the method SubscribeEvent ?

Thanks for your help,

Florian

EDIT

Sorry, here now the reference to "my previous question" : Subscribe to an event with Reflection

回答1:

Try something like this:

public void WriteTrace(object sender, EventArgs e, string eventName)
{
    Control c = (Control)sender;
    Console.WriteLine("Control: " + f.Name + ", Event: " + eventName);
}

public void SubscribeEvent(Control control, string eventName) {
    EventInfo eInfo = control.GetType().GetEvent(eventName);

    if (eInfo != null) {
        // create a dummy, using a closure to capture the eventName parameter
        // this is to make use of the C# closure mechanism
        EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eventName);

        // Delegate.Method returns the MethodInfo for the delegated method
        Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);

        eInfo.AddEventHandler(control, realDelegate);
    }
}