.netcore实现表达式的计算

发布时间 2023-07-14 17:17:59作者: 热情!

实现表达式的计算

比如要计算x+y+z,需要传入两个参数:一个参数是一个字符串:"x+y+z",另一个参数是一个字典:x=1,y=2,z=3

实现代码

点击查看代码
public static decimal Calculate(string expression, Dictionary<string, decimal> variables)
    {
        if (!string.IsNullOrWhiteSpace(expression))
        {
            try
            {
                // 将表达式中的每个变量替换成对应的数值
                foreach (var variable in variables)
                {
                    expression = expression.Replace(variable.Key, variable.Value.ToString());
                }
                // 构造DataTable,用Compute计算表达式
                var dt = new DataTable();
                var result = dt.Compute(expression, null);
                if (!decimal.TryParse(result.ToString(), out decimal value))
                {
                    throw Oops.Oh("计算错误");
                }

                return value;
            }
            catch
            {
                throw Oops.Oh("计算错误");
            }
        }
        else { return 0; }
    }

利用datatable的Compute方法还可以计算逻辑运算,
比如expression参数还可以传入IIF(h>2001, h*2,h)这样的式子
或者when case
还可以传入sum、svg这种函数计算。