如何通过反射和/或ILGenerator.Emit以编程方式调用方法?

时间:2019-02-27 05:32:27

标签: c# reflection reflection.emit

假设我有代码,可以在运行时接收方法调用列表:

    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
    }

如何以编程方式调用这些方法调用?

这是我到目前为止所拥有的,我感觉自己缺少一些东西。

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) 
             & stringArgs.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)
        {

        }
        */

    }

}

0 个答案:

没有答案