动态编译代码并调用

//调用
private string InvokeMethod(object[] paramArray, string method)
        {
            string[] methodArray = method.Split(',');
            MethodInfo methodInfo = null;
            ///动态程序集
            var dynamicAssembly = DynamicAssemblyHelp.buildCodeFile();
            object objHelloWorld = dynamicAssembly.CreateInstance(methodArray[0]);
            if (objHelloWorld != null)
            {
                methodInfo = objHelloWorld.GetType().GetMethod(methodArray[1]);
                if (methodInfo != null)
                {
                    return (string)methodInfo.Invoke(null, paramArray);             
                }
            }
            ///当前程序集
            Type type = Type.GetType(methodArray[0]);
            MethodInfo[] methos = type.GetMethods();
            methodInfo = type.GetMethod(methodArray[1]);
            if (methodInfo != null)
            {
                string newParam = (string)methodInfo.Invoke(null, paramArray);
                return newParam;
            }
            return string.Empty;
        }
        /// <summary>
        /// 编译-返回Assembly(判断文件是否改动避免重复加载)
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static Assembly buildCodeFile()
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "DynamicCs";
            DirectoryInfo directoryInfo = new DirectoryInfo(path);

            var LastWriteTime = directoryInfo.GetFiles().Max(m => m.LastWriteTime);
            if (updateFileTime==null || LastWriteTime > updateFileTime)
            {
               
                string pahtnext = $"{path}\\ProcessDutScript.cs";
                List<string> codelist = new List<string>();
                codelist.Add(pahtnext);
                var compilerResults = CompileDLL.RunCompile(codelist.ToArray());
                var result = CompileDLL.ConvertError(compilerResults);
                if (!string.IsNullOrEmpty(result))
                {
                    throw new Exception(result);
                }
                //编译新的
                dynamicAssembly = compilerResults.CompiledAssembly;
                updateFileTime = LastWriteTime;
            }
            return dynamicAssembly;

        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值