gpt4 book ai didi

c# - 将字符串转换为可执行代码性能

转载 作者:太空狗 更新时间:2023-10-29 23:05:58 26 4
gpt4 key购买 nike

我正在研究将字符串转换为可执行代码的解决方案。我的代码非常慢,执行时间为 4.7 秒。有更快的方法吗?

String: "5 * 5"

Output: 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();
}
}

最佳答案

好吧,有一个更简单的hack:

var _Result = new DataTable().Compute("5*5"); // _Result = 25
var _Result2 = new DataTable().Compute("5+5*5"); // _Result2 = 30

它还有更多的选择。请看一下 Documentation .

关于c# - 将字符串转换为可执行代码性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37070580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com