Ausführung von einfachen mathematischen Ausdrücken durch inline Compilierung.
Verwendung:
var val = Calculate("10 + 20 * 2 / 20");
Console.WriteLine(val);
var val2 = Calculate("(10 + 20) * 2 / 2");
Console.WriteLine(val2);
static double Calculate(string expression)
{
var options = new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } };
var provider = new CSharpCodeProvider();
var dlls = new[] { "mscorlib.dll", "System.Core.dll" };
var tempFile = Path.GetTempFileName() + ".dll";
var param = new CompilerParameters(dlls, tempFile, true);
param.GenerateInMemory = true;
param.GenerateExecutable = false;
var code = "using System; " +
"public class Calculator { " +
" public static double Run() { " +
" return " + expression + "; " +
" } " +
"}";
CompilerResults result = provider.CompileAssemblyFromSource(param, code);
if(result.Errors.Count > 0 ){
var errors = string.Join(" -> ", result.Errors.Cast<CompilerError>().Select(e => e.ErrorText));
throw new ArgumentException("expression is invalid. Compiler Result: " + errors);
}
var type = result.CompiledAssembly.GetTypes().First(t => t.Name == "Calculator");
var calcResult = (double)type.GetMethod("Run").Invoke(null, null);
return calcResult;
}
2 Kommentare zum Snippet