使用DynamicExpresso实现表达式求值

之前写了一篇Z.Expressions表达式计算的博客,直到最近才发现Z.Expressions不是免费的。Z.Expressions从2.0开始支持了NetCore,使用一段时期后会提示许可证到期,需要更新成最新的DLL,很不方便。最近在搜寻资料,发现了DynamicExpresso库,参考资料:https://www.cnblogs.com/songxingzhu/p/6737618.html

使用起来也很简单,一个简单的例子如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using DynamicExpresso;
 7 
 8 namespace ConsoleApplication1
 9 {
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             Interpreter interpreter = new Interpreter();
15             Dictionary<string, object> dict = new Dictionary<string, object>();
16 
17             dict.Add("a", 1.0);
18             dict.Add("b", 2);
19             dict.Add("d", 4);
20             dict.Add("e", 5);
21 
22             foreach (var v in dict)
23             {
24                 object value = v.Value;
25                 int para = 0;
26                 if (int.TryParse(v.Value.ToString(), out para))
27                 {
28                     value = (float)para;
29                 }
30                 interpreter.SetVariable(v.Key, value);
31             }
32 
33             Console.WriteLine(interpreter.Eval("a+b").ToString());
34             Console.WriteLine(interpreter.Eval("a*d").ToString());
35             Console.WriteLine(interpreter.Eval("b/d").ToString());
36         }
37     }
38 }

要注意的是除法运算时,如果都是整数,那么就存在为0的可能性,例如2/5。要避免这种情况可以将整数转换成浮点数,例如5改为5.0,这样计算结果为浮点数。

猜你喜欢

转载自www.cnblogs.com/kuaixue/p/13371698.html