我已经创建了一个小型应用程序,但我现在想合并某种可以通过列表框查看的日志记录类型。数据源可以从任意数量的地方发送。我创建了一个新的日志记录类,它将传递一个委托(delegate)。我认为我接近解决方案,但我收到 NullReferenceException 并且我不知道正确的解决方案。这是我正在尝试做的一个例子:
Class1 where the inbound streaming data is received.
class myClass
{
OtherClass otherClass = new OtherClass();
otherClass.SendSomeText(myString);
}
日志类
class OtherClass
{
public delegate void TextToBox(string s);
TextToBox textToBox;
Public OtherClass()
{
}
public OtherClass(TextToBox ttb)
{
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 pString)
{
listBox1.Items.Add(pString);
}
}
每当我在 myClass 中收到数据时,它就会抛出一个错误。如果您能提供任何帮助,我们将不胜感激。
请您参考如下方法:
删除空的构造函数并传入适当的委托(delegate)。
class OtherClass
{
public delegate void TextToBox(string s);
private readonly TextToBox textToBox;
public OtherClass(TextToBox textToBox)
{
if (textToBox == null)
throw new ArgumentNullException("textToBox");
this.textToBox = textToBox;
}
public void SendSomeText(string foo)
{
textToBox(foo);
}
}
