有时候需要,在程序中灵活的嵌入自定义的计算逻辑,使用C#加载JS脚本形式可以实现;
// 添加引用 using Microsoft.JScript; string jsStr = "var i=100; i++; i=i*100; var obj = {a:i};"; Stopwatch sw = new Stopwatch(); sw.Start(); object ret1 = null; try { ret1 = Eval.JScriptEvaluate(jsStr, VsaEngine.CreateEngine()); } catch (Exception ex) { MessageBox.Show(ex.StackTrace.ToString(), "执行失败", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } sw.Stop(); string res = ""; if (ret1 is ArrayObject) { // 数组 ArrayObject arr = (ArrayObject)ret1; res = arr[0].ToString(); } else if (ret1 is JSObject) { // 对象 JSObject obj = (JSObject)ret1; res = obj["a"].ToString(); } else { // 单值 res = ret1.ToString(); } MessageBox.Show(res + " 用时:" + sw.ElapsedMilliseconds.ToString() + "ms");