如何通过反射将参数传递给方法 [英] How to pass parameters to a method by reflection

查看:45
本文介绍了如何通过反射将参数传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的先例问题,我想将参数传递给方法"WriteTrace".但是我不知道该怎么做.

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

这里是实际代码:

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);
}

我是否使用这些信息创建一个从EventArgs派生的TraceEventArgs类?如何在SubscribeEvent方法中传递这些信息?

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

感谢您的帮助,

弗洛里安

编辑

对不起,这里是对我以前的问题"的引用:订阅事件与反思

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

推荐答案

尝试如下操作:

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);
    }
}

这篇关于如何通过反射将参数传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆