从c#生成MSIL代码,不带反射器/ ilspy

Til*_*ann 2 c# methods cil dynamic

我只对msil操作码等感兴趣.通常我用C#编程并尝试使用Reflection.Emit/MethodBuilder动态生成方法,但这需要操作码.

所以如果有可能通过将C#解析为msil并在方法构建器中使用它来动态生成方法,我感兴趣吗?

那么可以通过使用反射和C#代码在运行时动态生成方法吗?

Luk*_*keH 8

你可以看看表达式树,CodeDom,CSharpCodeProvider等.

using System.CodeDom.Compiler;
using Microsoft.CSharp;

// ...

string source = @"public static class C
                  {
                      public static void M(int i)
                      {
                          System.Console.WriteLine(""The answer is "" + i);
                      }
                  }";

Action<int> action;
using (var provider = new CSharpCodeProvider())
{
    var options = new CompilerParameters { GenerateInMemory = true };
    var results = provider.CompileAssemblyFromSource(options, source);
    var method = results.CompiledAssembly.GetType("C").GetMethod("M");
    action = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), method);
}
action(42);    // displays "The answer is 42"
Run Code Online (Sandbox Code Playgroud)