通过反射将方法分配给委托 [英] Assign method to delegate through reflection

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

问题描述

我在通过反射将方法动态分配给委托实例时遇到了困难.以下是我面临的情况的示例场景.

I got stuck up while dynamically assigning methods to a delegate instance through reflection. Below is a sample scenario of the situation i am faced with.

class Program
{
    static void Main(string[] args)
    {
        new DynamicDelegateTest().Test();            
    }
}

public class DynamicDelegateTest
{
    public void Test()
    {
        //This is what i target to do through reflection
        ABC objABC1 = new ABC();
        objABC1.Proc = Debugger;
        objABC1.Test("Helloz");

        //Implementing the same code through reflection
        ABC objABC = new ABC();
        MethodInfo MIDebugger = GetType().GetMethod("Debugger", BindingFlags.NonPublic | BindingFlags.Instance);
        FieldInfo MyProc = objABC.GetType().GetField("Proc", BindingFlags.Public | BindingFlags.Instance);

        //This is the point where I got stuck up
        MyProc.SetValue(objABC, MIDebugger);
        objABC.Test("QWERTY");  
    }

    void Debugger(object Tests)
    {
        Console.WriteLine(Tests);
    }
}

public class ABC
{
    public delegate void Delg(object P1);
    public Delg Proc;

    public void Test(object Tst)
    {
        if (Proc != null) Proc(Tst);
    }
}

请帮忙.

推荐答案

您需要使用 Delegate.CreateDelegate 来获取委托实例,而不是方法信息.对于非静态方法,这还包括目标实例.在这种情况下:

You need to use Delegate.CreateDelegate to get the delegate instance, rather than a method-info. For non-static methods this also includes the target instance. In this case:

object del = Delegate.CreateDelegate(MyProc.FieldType, this, MIDebugger);
MyProc.SetValue(objABC, del);

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

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