赞
踩
NCalc是一个数据表达式计算器,虽然说是一个数学表达式计算器,但是对于其中的数据表达式计算却并非仅仅用于数学表达的计算,他可以通过自定义的事件机制去处理很多的,各种各样的计算,但是他框架中去有点问题,在其EvaluationVisitor类中将大量的出现Case和If语句,好在他还提供了EvaluateFunction,对于每一个不同的Expression去创建不同的EvaluateFunction,去处理不同的处理方法,这对于系统来说是非常重要的。
例如:他可以进行数学计算:
string[] expressions = new string[]
{
"2 + 3 + 5",
"2 * 3 + 5",
"2 * (3 + 5)",
"2 * (2*(2*(2+1)))",
"10 % 3",
"true or false",
"not true",
"false || not (false and true)",
"3 > 2 and 1 <= (3-2)",
"3 % 2 != 10 % 3"
};
foreach (string expression in expressions)
Console.WriteLine("{0} = {1}",
expression,
new Expression(expression).Evaluate());
数据转换:
Assert.AreEqual(123456, new Expression("123456").Evaluate());
Assert.AreEqual(new DateTime(2001, 01, 01), new Expression("#01/01/2001#").Evaluate());
Assert.AreEqual(123.456f, new Expression("123.456").Evaluate());
Assert.AreEqual(true, new Expression("true").Evaluate());
Assert.AreEqual("true", new Expression("'true'").Evaluate());
Assert.AreEqual("azerty", new Expression("'azerty'").Evaluate());
Unicode转换:
Assert.AreEqual("経済協力開発機構", new Expression("'経済協力開発機構'").Evaluate());
Assert.AreEqual("Hello", new Expression(@"'/u0048/u0065/u006C/u006C/u006F'").Evaluate());
Assert.AreEqual("だ", new Expression(@"'/u3060'").Evaluate());
Assert.AreEqual("/u0100", new Expression(@"'/u0100'").Evaluate());
函数计算:
Assert.AreEqual(1M, new Expression("Abs(-1)").Evaluate());
Assert.AreEqual(0d, new Expression("Acos(1)").Evaluate());
Assert.AreEqual(0d, new Expression("Asin(0)").Evaluate());
Assert.AreEqual(0d, new Expression("Atan(0)").Evaluate());
Assert.AreEqual(2d, new Expression("Ceiling(1.5)").Evaluate());
Assert.AreEqual(1d, new Expression("Cos(0)").Evaluate());
Assert.AreEqual(1d, new Expression("Exp(0)").Evaluate());
Assert.AreEqual(1d, new Expression("Floor(1.5)").Evaluate());
Assert.AreEqual(-1d, new Expression("IEEERemainder(3,2)").Evaluate());
Assert.AreEqual(0d, new Expression("Log(1,10)").Evaluate());
Assert.AreEqual(0d, new Expression("Log10(1)").Evaluate());
Assert.AreEqual(9d, new Expression("Pow(3,2)").Evaluate());
Assert.AreEqual(3.22d, new Expression("Round(3.222,2)").Evaluate());
Assert.AreEqual(-1, new Expression("Sign(-10)").Evaluate());
Assert.AreEqual(0d, new Expression("Sin(0)").Evaluate());
Assert.AreEqual(2d, new Expression("Sqrt(4)").Evaluate());
Assert.AreEqual(0d, new Expression("Tan(0)").Evaluate());
另外我们还可以自定义计算方式去计算:
Expression e = new Expression("Replace([e], [a], [b])");
e.Parameters["e"] = "hello*hello*hello";
e.Parameters["a"] = "*";
e.Parameters["b"] = "%";
e.EvaluateFunction += delegate(string name, FunctionArgs args)
{
if (name == "Replace")
args.Result = ((string)args.Parameters[0].Evaluate()).Replace((string)args.Parameters[1].Evaluate(), (string)args.Parameters[2].Evaluate());
};
Console.WriteLine("{0} = {1}",
"Replace([e], [a], [b])",
e.Evaluate());
这些都是允许的。
下载地址:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。