简单表达式
Expression e = new Expression("2 + 3 * 5"); Debug.Assert(17 == e.Evaluate());
计算 .NET 数据类型
Debug.Assert(123456 == new Expression("123456").Evaluate()); // integers Debug.Assert(new DateTime(2001, 01, 01) == new Expression("#01/01/2001#").Evaluate()); // date and times Debug.Assert(123.456 == new Expression("123.456").Evaluate()); // floatinpoint numbers Debug.Assert(true == new Expression("true").Evaluate()); // booleans Debug.Assert("azerty" == new Expression("'azerty'").Evaluate()); // strings
处理 System.Math 所支持的函数
Debug.Assert(0 == new Expression("Sin(0)").Evaluate()); Debug.Assert(2 == new Expression("Sqrt(4)").Evaluate()); Debug.Assert(0 == new Expression("Tan(0)").Evaluate());
计算自定义函数
Expression e = new Expression("SecretOperation(3, 6)"); e.EvaluateFunction += delegate(string name, FunctionArgs args) { if (name == "SecretOperation") args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate(); }; Debug.Assert(9 == e.Evaluate());
处理 Unicode 字符
Debug.Assert("唐衣可俊" == new Expression("'唐衣可俊'").Evaluate()); Debug.Assert("Hello" == new Expression(@"'\u0048\u0065\u006C\u006C\u006F'"Evaluate()); Debug.Assert("だ" == new Expression(@"'\u3060'").Evaluate()); Debug.Assert("\u0100" == new Expression(@"'\u0100'").Evaluate());
定义参数
Expression e = new Expression("Round(Pow([Pi], 2) + Pow([Pi2], 2) + [X], 2)"); e.Parameters["Pi2"] = new Expression("Pi * [Pi]"); e.Parameters["X"] = 10; e.EvaluateParameter += delegate(string name, ParameterArgs args) { if (name == "Pi") args.Result = 3.14; }; Debug.Assert(117.07 == e.Evaluate());
参考链接
NCalc - Mathematical Expressions Evaluator for .NET
A Calculation Engine for .NET
State of the Art Expression Evaluation
标签:NCalc,Assert,Evaluate,args,笔记,学习,Debug,new,Expression From: https://www.cnblogs.com/shijiehaiyang/p/17492763.html