我正在寻找将字符串转换为可执行代码的解决方案。我的代码非常慢,并在4.7 seconds
执行。有没有更快的方法呢?
字符串:“5 * 5”
输出:25
代码:
class Program {
static void Main(string[] args) {
var value = "5 * 5";
Stopwatch sw = new Stopwatch();
sw.Start();
var test = Execute(value);
sw.Stop();
Debug.WriteLine($"Execute string at: {sw.Elapsed}");
}
private static object Execute(string content) {
var codeProvider = new CSharpCodeProvider();
var compilerParameters = new CompilerParameters {
GenerateExecutable = false,
GenerateInMemory = true
};
compilerParameters.ReferencedAssemblies.Add("system.dll");
string sourceCode = CreateExecuteMethodTemplate(content);
CompilerResults compilerResults = codeProvider.CompileAssemblyFromSource(compilerParameters, sourceCode);
Assembly assembly = compilerResults.CompiledAssembly;
Type type = assembly.GetType("Lab.Cal");
MethodInfo methodInfo = type.GetMethod("Execute");
return methodInfo.Invoke(null, null);
}
private static string CreateExecuteMethodTemplate(string content) {
var builder = new StringBuilder();
builder.Append("using System;");
builder.Append("\r\nnamespace Lab");
builder.Append("\r\n{");
builder.Append("\r\npublic sealed class Cal");
builder.Append("\r\n{");
builder.Append("\r\npublic static object Execute()");
builder.Append("\r\n{");
builder.AppendFormat("\r\nreturn {0};", content);
builder.Append("\r\n}");
builder.Append("\r\n}");
builder.Append("\r\n}");
return builder.ToString();
}
}
答案 0 :(得分:6)
嗯,有一个更简单的 hack :
var _Result = new DataTable().Compute("5*5"); // _Result = 25
var _Result2 = new DataTable().Compute("5+5*5"); // _Result2 = 30
它还有更多选择。请查看Documentation。