mercredi 2 septembre 2020

How can I subscribe to a delegate via C# Reflection?

I know a way to easily subscribe to events with Reflection, but now I am wondering is there a way to do the same thing with degates. Basically I need to call the '+=' operator of a delegate using Reflection. Here is a code snippet:

using System;

class Foo 
{
    public event Action Action1;
    public Action Action2;

    public void Call() 
    {
        Action1?.Invoke();
        Action2?.Invoke();
    }
}

class Program
{
    static void Main()
    {
        var foo = new Foo();

        // Subscribing to the event Action1 
        var eventInfo = typeof(Foo).GetEvent("Action1");
        Action tmp = () => { Console.WriteLine("Hello"); };
        var args = new object[] { tmp };
        eventInfo.AddMethod?.Invoke(foo, args);

        // Subscribing to the delegate Action2 with the += operator.
        // How can I do this with Reflection, instead ???
        foo.Action2 += () => { Console.WriteLine("Bye"); };

        foo.Call();
    }
}


Output:
Hello
Bye

I need to subscribe to Action2 using Reflection (in case Action2 was a private method, for instance). Any ideas how can I achieve this? Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire