2010-04-14 87 views
0

我一直在與試圖學習的代表玩耍,我遇到了一個小問題,我希望你能幫助我。使用委託來填充列表框

class myClass 
{ 
    OtherClass otherClass = new OtherClass(); // Needs Parameter 
    otherClass.SendSomeText(myString); 
} 

class OtherClass 
{ 
    public delegate void TextToBox(string s); 

    TextToBox textToBox; 

    public OtherClass(TextToBox ttb) // ***Problem*** 
    { 
     textToBox = ttb; 
    } 

    public void SendSomeText(string foo) 
    { 
     textToBox(foo); 
    } 
} 

形式:

public partial class MainForm : Form 
    { 
    OtherClass otherClass; 

    public MainForm() 
    { 
     InitializeComponent(); 
     otherClass = new OtherClass(this.TextToBox); 
    } 

    public void TextToBox(string aString) 
    { 
     listBox1.Items.Add(aString); 
    } 

} 

顯然,這並不編譯,因爲OtherClass構造正在尋找TextToBox作爲參數。你會如何推薦解決這個問題,以便我可以從myClass中將對象放入表單中的文本框中?

回答

2

您可以更改OtherClass喜歡的東西

class OtherClass 
{ 
    public delegate void TextToBox(string s); 

    TextToBox textToBox; 

    public OtherClass() 
    { 
    } 
    public OtherClass(TextToBox ttb) // ***Problem*** 
    { 
     textToBox = ttb; 
    } 

    public void SendSomeText(string foo) 
    { 
     if (textToBox != null) 
      textToBox(foo); 
    } 
} 

但我不太清楚你希望與

class myClass 
{ 
    OtherClass otherClass = new OtherClass(); // Needs Parameter 
    otherClass.SendSomeText(myString); 
} 
+1

我真的沒有在myClass的太多的控制才達到的。它是一個通過API接收的流。不知道爲什麼我沒有想到添加另一個構造函數。 – 2010-04-14 04:16:50