C# 将字符串动态编译为Assembly

 

/*
        using System.Reflection;
        using System.CodeDom;
        using System.CodeDom.Compiler;
         */
        private void Compiler()
        {
            CompilerParameters vCompilerParameters = new CompilerParameters();
            vCompilerParameters.GenerateExecutable = false;
            vCompilerParameters.GenerateInMemory = true;

            vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");//添加引用
            string vSource =
                "using System.Windows.Forms; " +//添加引用
                "public class ClassTemp " +
                "{ public ClassTemp(string ls_cs){MessageBox.Show(ls_cs);}" +
                "    public void Test(string ls_test) " +
                "    { " +
                "         MessageBox.Show(ls_test);" +
                "    } " +               
                "} ";
            CompilerResults vCompilerResults =
                CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource);

            Assembly vAssembly = vCompilerResults.CompiledAssembly;//至此编译出Assembly

            Object[] args1 = new Object[1];
            args1[0] = "test";
            object vTemp = vAssembly.CreateInstance("ClassTemp", true, System.Reflection.BindingFlags.Default, null, args1, null, null);//创建类的实例
            MethodInfo vTest = vTemp.GetType().GetMethod("Test");//从实例中取到方法放入MethodInfo中         

            Object[] args = new Object[1];
            args[0] = "test";
            vTest.Invoke(vTemp, args);//调用方法
        }

你可能感兴趣的:(assembly)