繁体   English   中英

使用委托来填充列表框

[英]Using a delegate to populate a listbox

我一直在与试图学习的代表们玩耍,我遇到了一个小问题,我希望您能为我提供帮助。

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中的对象放入表单的文本框中?

您可以将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); 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM