jeudi 21 février 2019

pass callback to class method created by reflection

I'm testing a concept, have a delegate:

 public delegate void PushMessageDelegate(string message);

I have a project dll with a method that has this type as a callback:

  public void RunReduction(PushMessageDelegate postMessage)
    {
        try
        {
            postMessage("Error Message");
            postMessage("Warning Message");
            postMessage("Info Message");
        }catch(Exception ex)
        {

            Debug.Print(ex.Message);

        }

    }        

I have a test console app that uses reflection to load the project dll. It also passes the method "PublishMessage" to the method reference.

 static void Main(string[] args)
    {
        Assembly reductionDLL = Assembly.LoadFrom(@"C:\\\...Reduceable.dll");
        string[] fullNameStrings = reductionDLL.FullName.Split(new char[] { ',' });
        string assemblyName = fullNameStrings[0];
        Type reductionClass = reductionDLL.GetType(assemblyName + ".ReductionCode");

        object obj = reductionDLL.CreateInstance(reductionClass.FullName);

        MethodInfo mi = reductionClass.GetMethod("RunReduction");

        mi.Invoke(obj, new object[1]{ (IReduce.PushMessageDelegate)PublishMessage });            

        Console.ReadLine();                                    
    }

    private static void PublishMessage(string message)
    {
        Console.WriteLine(message);
    }

It works, but in the mi.Invoke(....), this code:

  postMessage("Error Message");
            postMessage("Warning Message");
            postMessage("Info Message");

Executes the first postMessage("Error Message"), and returns to PublishMethod and displays it on the console. All good to this point, but it doesn't return to the RunReduction and execute postMessage("Warning Message"). It seems the Invoke is not what I'm needing. I need something that passes a reference to the RunReduction, I think. I appreciate the help in advance.





Aucun commentaire:

Enregistrer un commentaire