2010-04-24 76 views
3

我試圖在文本文件中編譯代碼以更改WinForms應用程序的主窗體上的TextBox中的值。 IE瀏覽器。在調用窗體中添加另一個帶有方法的分類。該表單有一個按鈕(button1)和一個文本框(textBox1)。CodeDom:編譯部分類

在文本文件中的代碼是:

this.textBox1.Text =的 「Hello World!」;

,代碼:

namespace WinFormCodeCompile 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      // Load code from file 
      StreamReader sReader = new StreamReader(@"Code.txt"); 
      string input = sReader.ReadToEnd(); 
      sReader.Close(); 

      // Code literal 
      string code = 
       @"using System; 
        using System.Windows.Forms; 

        namespace WinFormCodeCompile 
        { 
         public partial class Form1 : Form 
         { 

          public void UpdateText() 
          {" + input + @" 
          } 
         } 
        }"; 

      // Compile code 
      CSharpCodeProvider cProv = new CSharpCodeProvider(); 
      CompilerParameters cParams = new CompilerParameters(); 
      cParams.ReferencedAssemblies.Add("mscorlib.dll"); 
      cParams.ReferencedAssemblies.Add("System.dll"); 
      cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); 
      cParams.GenerateExecutable = false; 
      cParams.GenerateInMemory = true; 

      CompilerResults cResults = cProv.CompileAssemblyFromSource(cParams, code); 

      // Check for errors 
      if (cResults.Errors.Count != 0) 
      { 
       foreach (var er in cResults.Errors) 
       { 
        MessageBox.Show(er.ToString()); 
       } 
      } 
      else 
      { 
       // Attempt to execute method. 
       object obj = cResults.CompiledAssembly.CreateInstance("WinFormCodeCompile.Form1"); 
       Type t = obj.GetType(); 
       t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, null); 
      } 


     } 
    } 
} 

當我編譯的代碼中,CompilerResults返回說WinFormCodeCompile.Form1不包含TextBox1中定義的錯誤。

有沒有辦法動態創建另一個部分類文件到調用程序集並執行該代碼?

我想我錯過了一些非常簡單的東西。

+0

是你要完成的代碼編譯自code.txt將被「添加」到正在執行的應用程序中? – Axarydax 2010-04-24 06:21:41

+0

@Axarydax - 是的,但只是暫時的。看看是否可以更新文本文件中的一小段代碼並在運行時使用它。 – Inisheer 2010-04-24 06:25:15

回答

5

部分類無法跨越程序集 - 程序集是編譯單元,部分類在編譯後成爲單個類(在CLR級別上沒有等效的概念)。

1

你可以嘗試使用參數傳遞你要操作的對象,如:會產生這樣的片段作爲

// etc 
public void UpdateText(object passBox) 
{" + input + @" } 
// more etc 
t.InvokeMember("UpdateText", BindingFlags.InvokeMethod, null, obj, new object[] { this.textbox }); 

這樣的方式:

(passBox as TextBox).Text = "Hello World!!";