Dynamic Expresso

  • Available platforms: .NET Core 2.0, .NET 4.5, .NET 4.6.1
  1. Dynamic Expresso is an interpreter for simple C# statements written in .NET Standard 2.0. Dynamic Expresso embeds its own parsing logic, really interprets C# statements by converting it to .NET lambda expressions or delegates.
  2. Using Dynamic Expresso developers can create scriptable applications, execute .NET code without compilation or create dynamic linq statements.
  3. Statements are written using a subset of C# language specifications. Global variables or parameters can be injected and used inside expressions. It doesn't generate assembly but it creates an expression tree on the fly.

Git地址

https://github.com/davideicardi/DynamicExpresso

public class Program
    {
        private static Interpreter _target;
        static void Main(string[] args)
        {
            _target = new Interpreter();

            //返回指定数字的指定次幂
            Func<double, double, double> pow = (x, y) => Math.Pow(x, y);
            //开平方根
            Func<double, double> sqrt = (x) => Math.Sqrt(x);
            //最大值
            Func<double, double, double> max = (x, y) => Math.Max(x, y);
            //最小指
            Func<double, double, double> min = (x, y) => Math.Min(x, y);

            _target.SetFunction("pow", pow);
            _target.SetFunction("sqrt", sqrt);
            _target.SetFunction("max", max);
            _target.SetFunction("min", min);

            Console.WriteLine(_target.Eval("pow(3, 2)"));
            Console.WriteLine(_target.Eval("sqrt(9)"));
            Console.WriteLine(_target.Eval("max(3, 2)"));
            Console.WriteLine(_target.Eval("min(3, 2)"));

            //打印普通数学表达式计算的值
            string expression = "10/2+5+(10+5)*6-40";
            Console.WriteLine(_target.Eval(expression));
        }
    }

测试结果如下:


测试结果.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。