Created
March 23, 2017 22:46
-
-
Save keith9820/82f5878eefc76472d14d6d5f07bfe431 to your computer and use it in GitHub Desktop.
C# dynamic evaluation
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
private static object Eval(string __code) | |
{ | |
var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); | |
var p = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, null, true); | |
p.GenerateInMemory = true; | |
p.GenerateExecutable = false; | |
CompilerResults r = csc.CompileAssemblyFromSource(p, "using System; class p {public static object c(){"+__code+"}}"); | |
if (r.Errors.Count > 0) | |
{ | |
r.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText)); | |
return null; | |
} | |
System.Reflection.Assembly a = r.CompiledAssembly; | |
MethodInfo o = a.CreateInstance("p").GetType().GetMethod("c"); | |
return o.Invoke(o, null); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment