簡體   English   中英

從c#生成MSIL代碼,不帶反射器/ ilspy

[英]Generate MSIL Code from c# without reflector/ilspy

我只對msil操作碼等感興趣。通常我用C#編程並試圖用Reflection.Emit / MethodBuilder動態生成方法,但這需要操作碼。

所以如果有可能通過將C#解析為msil並在方法構建器中使用它來動態生成方法,我感興趣嗎?

那么可以通過使用反射和C#代碼在運行時動態生成方法嗎?

您可以查看表達式樹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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM