c# 执行js 动态编译

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)
        {
            //编译的参数
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = true;
            CompilerResults results = _provider.CompileAssemblyFromSource(parameters, scriptStr);
            Assembly assembly = results.CompiledAssembly;

            //动态编译脚本中的内容
            _evaluateType = assembly.GetType("fhs.MyJs");

            //执行指定的方法并传参数
            object retObj = _evaluateType.InvokeMember(jsMethodName, BindingFlags.InvokeMethod,
                        null, null, testParams);

            return retObj;
        }

    }
}

c# 执行js 动态编译

上一篇:Windows Server 2008R2服务器安装及设置教程


下一篇:C#文件相关操作