2010-04-14 89 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