准备:
创建一个空项目,nuget查找并安装ExpressionEvaluator
示例:
using ExpressionEvaluator;
using System;
一、计算简单表达式
public string Test1()
{
return SimpleEval("0.1*(Math.Pow(10,2)+20)");
}
/// <summary>
/// 简单数值计算
/// </summary>
/// <param name="str">纯表达式</param>
/// <returns>返回值</returns>
public string SimpleEval(string str)
{
var types = new TypeRegistry();
types.RegisterDefaultTypes();
var expression = new CompiledExpression(str) { TypeRegistry = types };
var result = expression.Eval();
Console.WriteLine("简单数值计算: {0}", result);
return result.ToString();
}
二、计算复杂表达式
public class Result
{
public double Days { get; set; }
public double Bonus { get; set; }
}
/// <summary>
/// 变量字段的计算
/// </summary>
/// <param name="str"></param>
/// <param name="type"></param>
/// <returns></returns>
public string FieldEval(string str, Object type)
{
//注册
var reg = new TypeRegistry();
reg.RegisterSymbol("Result", type);
//如果要使用Math函数,还就注册这个
//reg.RegisterDefaultTypes();
//编译
var p = new CompiledExpression(str) { TypeRegistry = reg };
p.Compile();
//计算
Console.WriteLine("变量字段计算: {0}", p.Eval());
return p.Eval().ToString();
}
public string Test2()
{
string[] strFields = new string[] { "Days", "Bonus" };
string exp = "(Days*10)+(Bonus/2)";
for (int i = 0; i < strFields.Length; i++)
{
if (exp.Contains(strFields[i]))
{
exp = exp.Replace(strFields[i], "Result." + strFields[i]);
}
}
Result re = new Result()
{
Days = 200,
Bonus = 500
};
var result = this.FieldEval(exp, re);
return result;
}