使用 C# 将字符串表达式转换为整数值
抱歉,如果这个问题已经得到解答,但我没有找到合适的答案。 我在 C# 中有一个字符串表达式,需要将其转换为 int 或十进制值。
例如:
string strExp = "10+20+30";
输出应该是 60。
我该怎么做???
Sorry if this question is answered already, but I didn't find a suitable answer.
I am having a string expression in C# which I need to convert to an int or decimal value.
For example:
string strExp = "10+20+30";
the output should be 60.
how shall I do that???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Fwiw,.NET 框架中内置了一个表达式解析器。 DataTable.Compute () 方法使用它:
但请注意,它不是一个功能非常齐全的方法。仅简单表达式,即您在 SQL 查询中找到的类型。
Fwiw, there is an expression parser built into the .NET framework. The DataTable.Compute() method uses it:
Beware however that it isn't a very full-featured one. Simple expressions only, the kind you'd find in a SQL query.
使用NCalc:稳定、简单且功能强大
Use NCalc : stable, simple, and powerful
.NET 中没有内置任何内容,因此您需要使用数学表达式解析器并使用它来获取结果。
这里就是其中之一。还有一对 文章。
There is nothing built into .NET, so you will need to use a mathematical expression parser and use that to get the result.
Here is one. And a couple of articles.
您需要通过分隔数字和运算符(+、-、*、/ 等)来解析字符串。可以使用.TryParse 命令(例如Int32.TryParse())将数字转换为整数或小数。可以使用 switch 语句来处理运算符。您希望能够处理的表达式类型越复杂,处理起来就越困难。您可以使用递归来处理括号中的子表达式。
编辑:我本来想找到一些示例文章,但我看到 Oded 已经发布了一些。
You'll need to parse the string by separating the numbers and the operators (+,-,*,/, etc.). The numbers can be converted to integers or decimals using the .TryParse commands (e.g. Int32.TryParse()). The operators can be handled with a switch statement. The more complicated the types of expressions you want to be able to handle the harder it's going to be. You could use recursion to handle sub-expressions in parentheses.
Edit: I was going to find some sample articles but I see that Oded has already posted some.
也许使用脚本库 - IronPython (python)、cs-script (c#) 甚至 MSScriptControl (VBscript) - 然后您可以将字符串表达式传递到库进行评估。
使用 MSScript 控件的示例:
使用 MSScriptControl;
...
ScriptControl ScriptEngine = new ScriptControlClass();
ScriptEngine.Language = "VBScript";
字符串表达式=“10+20+30”;
对象结果 = ScriptEngine.Eval(expr);
小数 d = Convert.ToDecimal(结果);
Perhaps use a scripting library - IronPython (python), cs-script (c#) or even MSScriptControl (VBscript) - you can then pass your string expression to the library for evaluation.
Example using MSScript Control:
using MSScriptControl;
...
ScriptControl ScriptEngine = new ScriptControlClass();
ScriptEngine.Language = "VBScript";
string expr = "10+20+30";
object result = ScriptEngine.Eval(expr);
decimal d = Convert.ToDecimal(result);