• netcore 下的 Javascript 表达式求值


    netframework 下的 codedom 代码已经不能用了,会报错,改用 Jint 来写:

    先安装包

    install-package Jint

    核心代码

        using Jint;
        public class JsEvaluator
        {
            static Engine _engine;
            static JsEvaluator()
            {
                _engine = new Engine();
            }
    
            /// <summary>解析表达式值</summary>
            public object Eval(string expression)
            {
                var cmd = $"eval({expression.Quote()})";
                return _engine.Execute(cmd).GetCompletionValue().ToObject();
            }
    
            /// <summary>
            /// 转化为日期时间必须用这个函数。格式如:new Date('2018/01/01 12:00:00')
            /// </summary>
            public DateTime EvalDateTime(string expression)
            {
                var cmd = $"eval({expression.Quote()}).toLocaleString()";
                var o = _engine.Execute(cmd).GetCompletionValue().ToObject();
                return Convert.ToDateTime(o);
            }
        }

    可以快乐的测试了

    var eval = new JsEvaluator();
    var b = eval.Eval("5 > 4");
    var d = eval.Eval("2.5");
    var o = eval.Eval("new Date()");
    var t = eval.EvalDateTime("new Date('2018/01/01 12:00:00')");

     

  • 相关阅读:
    hdu 5072 Coprime (容斥)
    洛谷 P1411 树 (树形dp)
    Tr/ee AtCoder
    sys.path
    uname
    sys.platform
    Eclipse Basic
    Eclipse Color Theme
    Pydev
    scons
  • 原文地址:https://www.cnblogs.com/surfsky/p/12918607.html
Copyright © 2020-2023  润新知