mardi 26 février 2019

How to programmatically call a method via Reflection and/or ILGenerator.Emit?

Suppose I have code, that receives list of method calls during runtime:

    static void Main(string[] args)
    {
        var foo = new Foo();
        var code0 = "DoThis()";
        foo.DynamicCalls(code0);
        var code1 = "DoThis(1)";
        foo.DynamicCalls(code1);
        var code2 = $"DoThat({"Hey"})";
        foo.DynamicCalls(code2);
        // and so on
    }

How do I programmatically invoke these method calls?

This is what I have so far and I feel like I am missing something.

public class Foo
{
    public void DoThis()
    {
        Console.WriteLine($"Doing this {0}");
    }
    public void DoThis(int count)
    {
        Console.WriteLine($"Doing this {count}");
    }

    public void DoThat(string message)
    {
        Console.WriteLine($"Doing that {message}");
    }

    public void DynamicCalls(string codeToExecute)
    {

        EmitCompileAndExecute(codeToExecute); //how?

        /*
        var targetMethodName = string.Concat(codeToExecute.TakeWhile(z => z != '('));
        var stringArgs = string.Concat(codeToExecute.SkipWhile(z => z != '(')
            .Skip(1)
            .TakeWhile(z => z != ')'))?.Trim()
            .Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

        var methodInfo = this.GetType().GetTypeInfo().GetRuntimeMethods()
            .SingleOrDefault(z => z.Name.Equals(targetMethodName, StringComparison.OrdinalIgnoreCase) & args.Length == z.GetParameters().Length);


        // mi.Invoke(this, stringArgs); // args need to match type!


        DynamicMethod dm = new DynamicMethod("foo", null, null);
        ILGenerator gen = dm.GetILGenerator();
        foreach (string arg in stringArgs)
        {

        }
        */

    }

}





Aucun commentaire:

Enregistrer un commentaire