我一直在和想要学习的代表一起玩,我遇到了一个小问题我希望你可以帮助我。
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中将一个对象放到表格的文本框中?
答案 0 :(得分:2)
您可以将其他类更改为
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);
}