Mo *_*ish 2 c# math equation equations
可能重复:
我需要一个快速的运行时表达式解析器
如果有人在我的页面上的文本框中键入x*y ^ z来计算后面代码中的等式并得到结果,我怎么做呢?
使用内置的 .NET 功能,用户/sf/users/116901571/以字符串形式回答运算符:
“如果你所需要的只是简单的算术,那就这样做吧。
DataTable temp = new DataTable();
Console.WriteLine(temp.Compute("15 / 3",string.Empty));
Run Code Online (Sandbox Code Playgroud)
编辑:更多信息。查看 MSDN 文档以了解 System.Data.DataColumn 类的 Expression 属性。“表达式语法”上的内容概述了除算术运算符外还可以使用的命令列表。(例如 IIF、LEN 等)。”
编辑 2:为方便起见,您可以将其放入一个小函数中,例如:
public string Eval(string expr)
{
var temp = new System.Data.DataTable();
string result = null;
try
{
result = $"{temp.Compute(expr, string.Empty)}";
}
catch (System.Data.EvaluateException ex)
{
if (ex.Message.ToLower().Contains("cannot find column"))
throw new System.Data.SyntaxErrorException($"Syntax error: Invalid expression: '{expr}'."
+ " Variables as operands are not supported.");
else
throw;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
所以你可以像这样使用它:
Console.WriteLine(Eval("15 * (3 + 5) / (7 - 2)"));
Run Code Online (Sandbox Code Playgroud)
给出预期的输出:
24
请注意,错误处理程序有助于处理由使用此处不允许的变量引起的异常。示例:Eval("a")- 而不是 return "Cannot find column [a]",这在此上下文中没有多大意义(我们不在数据库上下文中使用它)它正在返回"Syntax error: Invalid expression: 'a'. Variables as operands are not supported."
在DotNetFiddle上运行它