欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

NetCore中使用DynamicExpresso、Z.Expressions、LambdaParser进行安字符串求值

例子如下:

Z.Expressions从2.0开始支持了NetCore,但是收费的。其它两者免费。建议使用DynamicExpresso,免费而且速度快。LambdaParser目前支持太少。

static void Main(string[] args)
        {

            Console.OutputEncoding = Encoding.Unicode;

            System.Diagnostics.Stopwatch sp = new Stopwatch();
            sp.Start();
            var code = "i<100&&s.Contains(\"测试\")";
            var interpreter = new DynamicExpresso.Interpreter();
            var result = interpreter.ParseAsDelegate<Func<int, string, bool>>(code, "i", "s");
            //var result = interpreter.ParseAsExpression<Func<int, string, bool>>(code, "i", "s").Compile();
            for (int i = 0; i < 18000000; i++)
            {
                var v = result(i, "我在测试" + i);//2213ms
                //Console.WriteLine(v);
            }
            sp.Stop();
            Console.WriteLine("time:" + sp.ElapsedMilliseconds + "ms");

            //System.Diagnostics.Stopwatch sp = new Stopwatch();
            //sp.Start();
            ////var code = @"
            ////     var list = new List<int>() { 1, 2, 3, 4, x };
            ////        var filter = list.Where(x => x < 4);
            ////        return filter.Sum(x => x); ";
            //var code = "i<100&&s.Contains(\"测试\")";
            ////var result = Z.Expressions.Eval.Compile<Func<int, string, bool>>(code, "i", "s");

            //for (int i = 0; i < 100000; i++)
            //{
            //    var v = result(i, "我爱测试");
            //    //Console.WriteLine(v);
            //}
            //sp.Stop();
            //Console.WriteLine("time:" + sp.ElapsedMilliseconds + "ms");

            //var parse = new LambdaParser();
            //while (true)
            //{
            //    try
            //    {
            //        Console.WriteLine(new string('_', 20));
            //        var dics = new Dictionary<string, object>();
            //        dics.Add("x1", 32.0);
            //        dics.Add("x2", 23.0);
            //        dics.Add("x3", 34.5);
            //        dics.Add("x4", 34.5);
            //        dics.Add("s1", "my name is xxxxzhu!");
            //        dics.Add("b1", true);
            //        foreach (var item in dics)
            //        {
            //            Console.WriteLine(item.Key + "\t" + item.Value);
            //        }
            //        Console.WriteLine(new string('_', 20));
            //        Console.WriteLine("expr:");
            //        var expr = Console.ReadLine();
            //        var value = parse.Eval(expr, dics);
            //        Console.WriteLine("value======================" + value);
            //    }
            //    catch (Exception ex) { Console.WriteLine("error====================:" + ex.Message); }
            //}
        }

 

posted @ 2017-04-20 11:03  宋兴柱  阅读(3205)  评论(0编辑  收藏  举报