2012-05-29 41 views
2

我剛剛對msil操作碼等感興趣。 通常我在C#中編程並嘗試使用Reflection.Emit/MethodBuilder動態生成方法,但這需要操作碼。從c#生成MSIL代碼沒有反射器/ ilspy

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

那麼是否有可能通過使用反射和C#代碼在運行時動態生成方法?

+0

是的,它是可能的。查看CodeDom,Expression Trees等。 –

回答

8

你可以看看expression treesCodeDomCSharpCodeProvider

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" 
+0

Downvoter:請解釋爲什麼? – LukeH