本文實例講述了C#執(zhí)行js動態(tài)編譯的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:
復(fù)制代碼代碼如下:
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace webpro
{
public class JScripta
{
private static readonly CodeDomProvider _provider = new Microsoft.JScript.JScriptCodeProvider();
private static Type _evaluateType;
private const string scriptStr = @"package fhs
{
public class MyJs
{
public static function test1(paramr1)
{
var retString = paramr1+ '是無敵的!';
return retString;
}
}
}";
public static object JScriptRun(string jsMethodName,object[] testParams)
{
//編譯的參數(shù)
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results = _provider.CompileAssemblyFromSource(parameters, scriptStr);
Assembly assembly = results.CompiledAssembly;
//動態(tài)編譯腳本中的內(nèi)容
_evaluateType = assembly.GetType("fhs.MyJs");
//執(zhí)行指定的方法并傳參數(shù)
object retObj = _evaluateType.InvokeMember(jsMethodName, BindingFlags.InvokeMethod,
null, null, testParams);
return retObj;
}
}
}
希望本文所述對大家的C#程序設(shè)計有所幫助。