1

我已经创建了一个小型应用程序,但现在我想合并一些可以通过列表框查看的日志记录。数据源可以从任意数量的地方发送。我创建了一个新的日志类,它将传入一个委托。我认为我接近解决方案,但我收到 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 中收到数据时,它都会引发错误。您可以提供的任何帮助将不胜感激。

4

4 回答 4

1

删除空的构造函数并传入正确的委托。

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);
   }
}
于 2010-04-14T17:47:12.620 回答
1

更改您的 OtherClass 以检查是否为空:

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

   TextToBox textToBox;

    Public OtherClass()
    {
    }

   public OtherClass(TextToBox ttb) 
   {
       textToBox = ttb;
   }

   public void SendSomeText(string foo)
   {
       var handler = this.TextToBox;
       if(handler != null)
       {
           textToBox(foo);
       }
   }
}

现在你得到异常的原因是因为在你的 myClass 中,当你创建一个新的 OtherClass 时,你没有提供委托应该“指向”的方法。因此,当您调用 OtherClass 时textToBox(foo);,它背后没有任何方法,并且它会爆炸。

于 2010-04-14T17:50:59.037 回答
1

您应该在 myClass 构造函数中传递您在 MainForm 中创建的 OtherClass 实例,不要在 myClass 中创建 OtherClass 实例,它不是您附加处理程序的实例。

于 2010-04-14T17:56:01.477 回答
1

在 myClass 中,您没有调用采用 TextToBox 的重载 OtherClass 构造函数,因此 textToBox(foo) 失败,因为尚未设置 textToBox。

你能显示 myClass 被初始化和调用的代码吗?

于 2010-04-14T17:58:22.907 回答