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')");
转载请注明出处:http://surfsky.cnblogs.com