使用C#将字符串表达式转换为整数值

Jan*_*ana 11 c# string integer

很抱歉,如果已经回答了这个问题,但我找不到合适的答案.我在C#中有一个字符串表达式,我需要将其转换为int或decimal值.

例如:

string strExp = "10+20+30";
Run Code Online (Sandbox Code Playgroud)

输出应为60.

我该怎么办?

Ode*_*ded 6

.NET中没有内置任何内容,因此您需要使用数学表达式解析器并使用它来获取结果.

是一个.和夫妇文章.


Cat*_*ICU 6

使用NCalc:稳定,简单,功能强大


Han*_*ant 5

Fwiw,.NET框架中内置了一个表达式解析器.所述DataTable.Compute()方法使用它:

using System;
using System.Data;

class Program {
    static void Main(string[] args) {
        var expr = "10 + 20 + 30";
        var result = new DataTable().Compute(expr, null);
        Console.WriteLine(result);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

但请注意,它不是一个非常全功能的.只有简单的表达式,你在SQL查询中找到的那种.