C performs the js dynamic compilation method
- 2020-12-18 01:54:27
- OfStack
This article shows an example of how C# performs dynamic compilation of js. Share to everybody for everybody reference. Specific implementation methods are as follows:
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+ ' Is invincible !';
return retString;
}
}
}";
public static object JScriptRun(string jsMethodName,object[] testParams)
{
// Compiled parameters
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
CompilerResults results = _provider.CompileAssemblyFromSource(parameters, scriptStr);
Assembly assembly = results.CompiledAssembly;
// Dynamically compiling the contents of the script
_evaluateType = assembly.GetType("fhs.MyJs");
// Executes the specified method and passes the parameters
object retObj = _evaluateType.InvokeMember(jsMethodName, BindingFlags.InvokeMethod,
null, null, testParams);
return retObj;
}
}
}
Hopefully this article has helped you with your C# programming.