Assign delegation method through reflection

I am stuck dynamically assigning methods to a delegate instance through reflection. The following is an example of a scenario of the situation I encountered.

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

Please, help.

+3
source share
1 answer

You need to use Delegate.CreateDelegateit to get a delegate instance, not the info method. 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);
+10
source

Source: https://habr.com/ru/post/1754243/


All Articles