C# 如何以代码形式执行我的字符串
我现在正在做一个计算器。我知道如何写逻辑,但我很好奇是否可以用我将要解释的方式来完成C# 如何以代码形式执行我的字符串,c#,C#,我现在正在做一个计算器。我知道如何写逻辑,但我很好奇是否可以用我将要解释的方式来完成 String str = "12 + 43 * (12 / 2)"; int answer; answer = str.magic(); //str.magic is the same as answer = 12 + 43 * (12 / 2); 现在我想要的是如何将str转换为可执行代码 您只需使用NCalc库即可获得更多信息。 您可以从下载该dll文件 示例: NCalc.Expressio
String str = "12 + 43 * (12 / 2)";
int answer;
answer = str.magic();
//str.magic is the same as
answer = 12 + 43 * (12 / 2);
现在我想要的是如何将str转换为可执行代码 您只需使用NCalc库即可获得更多信息。 您可以从下载该dll文件 示例:
NCalc.Expression exp= new NCalc.Expression("(12*3)-29");
object obj = exp.Evaluate();
MessageBox.Show(obj.ToString());
您可以使用CodeDom获得“本机”C#解析器。 (您应该改进错误处理。)
是的,可以做到。谷歌表达式解析器看看这个我有点困惑-你想问什么?你说你“知道如何写逻辑”,然后问你如何实际执行任务?
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
...
static void Main()
{
double? result = Calculate("12 + 43 * (12 / 2)");
}
static double? Calculate(string formula)
{
double result;
try
{
CompilerParameters compilerParameters = new CompilerParameters
{
GenerateInMemory = true,
TreatWarningsAsErrors = false,
GenerateExecutable = false,
};
string[] referencedAssemblies = { "System.dll" };
compilerParameters.ReferencedAssemblies.AddRange(referencedAssemblies);
const string codeTemplate = "using System;public class Dynamic {{static public double Calculate(){{return {0};}}}}";
string code = string.Format(codeTemplate, formula);
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParameters, new string[]{code});
if (compilerResults.Errors.HasErrors)
throw new Exception();
Module module = compilerResults.CompiledAssembly.GetModules()[0];
Type type = module.GetType("Dynamic");
MethodInfo method = type.GetMethod("Calculate");
result = (double)(method.Invoke(null, null));
}
catch (Exception)
{
return null;
}
return result;
}