动态编译执行代码

来源:互联网 发布:c语言预处理指令放在哪 编辑:程序博客网 时间:2024/06/05 07:32


        string code = txtCode.Text;
        /* code值:
            public class MyClass{
                public static string Show(){
                    return "HEllo";
                }
            }
         */


        CompilerParameters cp = new CompilerParameters();
        cp.ReferencedAssemblies.Add("System.dll");

        CodeDomProvider comp = new CSharpCodeProvider();

    //编译代码

        CompilerResults cr=comp.CompileAssemblyFromSource(cp, code);
        if (cr.Errors.HasErrors)
        {
            lblResult.Text = cr.Errors.ToString();
        }

        else {

      //执行静态方法

            Assembly a = cr.CompiledAssembly;
            Type t = a.GetType("MyClass");
            MethodInfo mi = t.GetMethod("Show");
            lblResult.Text=mi.Invoke(a,null).ToString();
        }
0 0
原创粉丝点击