不介绍各种js引擎了,只说两种方法
方法一:最古老的方法
private static Type type = Type.GetTypeFromProgID("ScriptControl"); public static string JavaScriptEval(string strJs, string main) { object scriptControl = ExecJsHelper.GetScriptControl(); ExecJsHelper.SetScriptControlType(strJs, scriptControl); return ExecJsHelper.type.InvokeMember("Eval", BindingFlags.InvokeMethod, null, scriptControl, new object[] { main }).ToString(); } private static Type SetScriptControlType(string strJs, object obj) { ExecJsHelper.type.InvokeMember("Language", BindingFlags.SetProperty, null, obj, new object[] { "JScript" }); ExecJsHelper.type.InvokeMember("AddCode", BindingFlags.InvokeMethod, null, obj, new object[] { strJs }); return ExecJsHelper.type; } private static object GetScriptControl() { return Activator.CreateInstance(ExecJsHelper.type); }
方法二:v8.net
需要添加引用
V8.Net.dll
V8.Net.SharedTypes.dll
然后需要将V8_Net_Proxy_x64.dll和V8_Net_Proxy_x86.dll两个文件放到程序输出目录下,Web应用放到bin目录下
public static string JSEval(string strjs, string func) { var V8Engine = new V8Engine(); Handle result = V8Engine.Execute(strjs + ";" + func); return result.ToString(); }
需要注意的是,方法一有时候执行的结果和方法二不一致,此时以方法二为准!
已有 5932 位网友参与,快来吐槽:
发表评论