運行時動態將字符串編譯爲C#可執行代碼

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);

        }
相關文章
相關標籤/搜索