Created
July 13, 2016 21:16
-
-
Save keith9820/1e509ca673ea4a7cc971d9ee0cea690a to your computer and use it in GitHub Desktop.
C# Eval method
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