从 c# 生成 MSIL 代码,无需反射器/ilspy

本文关键字:反射器 ilspy 生成 MSIL 代码 | 更新日期: 2023-09-27 18:35:33

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

所以我很想知道是否有可能通过将 C# 解析为 msil 并在方法生成器中使用它来动态生成方法?

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

从 c# 生成 MSIL 代码,无需反射器/ilspy

你可以看看表达式树、CodeDomCSharpCodeProvider等。

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"