简体   繁体   中英

Generate MSIL Code from c# without reflector/ilspy

I just got interested in msil opcode etc. Normally I'm programming in C# and tried to generate Methods dynamically with Reflection.Emit / MethodBuilder but this requires opcode.

So I was intrested if it's possible to generate Methods dynamically with parsing C# to msil and using this in the Method Builder?

So is it possible to generate methods dynamically at runtime by using reflection and C# code ?

You could take a look at expression trees , CodeDom , CSharpCodeProvider etc.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM