Last active
December 17, 2015 00:49
-
-
Save ialex32x/5523557 to your computer and use it in GitHub Desktop.
C# compiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Sample | |
{ | |
class Test | |
{ | |
public static System.Reflection.Assembly Compile(string source) | |
{ | |
var p = new Microsoft.CSharp.CSharpCodeProvider(); | |
var c = p.CreateCompiler(); | |
var parameters = new System.CodeDom.Compiler.CompilerParameters(); | |
parameters.GenerateExecutable = false; | |
var r = c.CompileAssemblyFromSource(parameters, string.Format( | |
"using System; namespace Foo {{ public static class MethodStub {{ public static void foo() {{ {0} }} }} }}", | |
source)); | |
return r.CompiledAssembly; | |
} | |
public static void Call(System.Reflection.Assembly a, string method) | |
{ | |
var t = a.GetType("Foo.MethodStub"); | |
t.InvokeMember(method, | |
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod, | |
System.Type.DefaultBinder, null, null); | |
} | |
[STAThread] | |
static void Main(string[] args) | |
{ | |
var a1 = Compile("Console.WriteLine(\"Hello, Earth\");"); | |
var a2 = Compile("Console.WriteLine(\"Hello, Moon\");"); | |
Call(a2, "foo"); | |
Call(a1, "foo"); | |
System.Console.ReadKey(true); | |
} | |
} | |
} |
Author
ialex32x
commented
May 6, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment