运行时动态将字符串编译为C#可执行代码

时间:2021-11-23 03:54:02
private void button1_Click(object sender, EventArgs e)
        {
            CSharpCodeProvider CSharp = new CSharpCodeProvider();

            String[] dll = { "System.dll", "System.Windows.Forms.dll" };

            CompilerParameters 编译参数 = new CompilerParameters(dll);

            编译参数.GenerateExecutable = false;

            编译参数.GenerateInMemory = true;

            string 代码串 = this.textBox1.Text;

            CompilerResults 结果 = CSharp.CompileAssemblyFromSource(编译参数, 代

码串);

            Assembly 程序集 = 结果.CompiledAssembly;

            object 动态对象 = 程序集.CreateInstance("wxd");

            MethodInfo 方法 = 动态对象.GetType().GetMethod("setText");

            object[] 参数 = { this.button1 };

            object s = 方法.Invoke(动态对象, 参数);

            System.Console.WriteLine(s);

        }