zoukankan      html  css  js  c++  java
  • 使用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,这样计算结果为浮点数。

    作者:快雪
    本文版权归作者所有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。
  • 相关阅读:
    面试题33:把数组排成最小的数
    面试题32:从1到n整数中1出现的次数
    面试题31:连续子数组的最大和
    HTTPS 及加密信息全解析
    面试题30:最小的k个数
    linux退出vi
    linux清除当前屏幕
    java web开发环境配置
    jQuery积累
    html5离线应用详摘
  • 原文地址:https://www.cnblogs.com/kuaixue/p/13371698.html
Copyright © 2011-2022 走看看