c# 动态编译方法

今天写了一个Excel导入数据库验证的方法,验证规则是存到数据库里了,对于不同的Excel调用不同的验证方法。
代码:
        
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Globalization;


        CompilerResults result=null;
        /// <summary>
        /// 生成一个验证方法
        /// </summary>
        /// <returns></returns>
        public void DynamicInvokeValidate() {

            string code = this.compilerMethod();//拼接字符串方法。            

            //设置编译器对象
            CSharpCodeProvider csprovider = new CSharpCodeProvider();
            ICodeCompiler icompiler = csprovider.CreateCompiler();

            //设置编译环境
            CompilerParameters options = new CompilerParameters();  //参数对象
            options.ReferencedAssemblies.Add("System.dll");   //加载引用的程序集
            options.ReferencedAssemblies.Add("System.Data.dll");
            options.GenerateInMemory = true;     //是否输出到内存
            options.OutputAssembly="DynamicValidate"; //输出程序集的名称

            //开始编译
            CodeSnippetCompileUnit codesnipper = new CodeSnippetCompileUnit(code);
            this.result = icompiler.CompileAssemblyFromDom(options, codesnipper);
        }

            public string DynamicMethod(DataRow row) {
            try
            {
                object[] parameters ={ row };
                Type t = this.result.CompiledAssembly.GetType("IngoingExcel.Validate");

                object obj = this.result.CompiledAssembly.CreateInstance("IngoingExcel.Validate", false, BindingFlags.Default, null, new object[] { }, CultureInfo.CurrentCulture, null);

                object str = t.InvokeMember("ValidateIngoingData", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, obj, parameters);

                return str.ToString();
            }
            catch
            {
                return "调用验证方法出错,请联系管理员.";                  
            }           
        }

你可能感兴趣的:(动态编译)