开发者

Logging class using delegates (NullReferenceException)

I have created a small application but I would now like to incorporate some type of log开发者_StackOverflow社区ging that can be viewed via listbox. The source of the data can be sent from any number of places. I have created a new logging class that will pass in a delegate. I think Im close to a solution but Im receiving a NullReferenceException and I don’t know the proper solution. Here is an example of what Im trying to do:

Class1 where the inbound streaming data is received.
class myClass
{
   OtherClass otherClass = new OtherClass();
   otherClass.SendSomeText(myString);
}

Logging Class

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);
   }
}

The Form

public partial class MainForm : Form
   {
   OtherClass otherClass;

   public MainForm()
   {
       InitializeComponent();
       otherClass = new OtherClass(this.TextToBox);
   }

   public void TextToBox(string pString)
   {
       listBox1.Items.Add(pString);
   }

}

Whenever I receive data in myClass, its throwing an error. Any help you could give would be appreciated.


Remove the empty constructor and pass the proper delegate in.

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);
   }
}


Change your OtherClass to check for null:

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);
       }
   }
}

Now the reason you're getting the exception though is because in your myClass when you're creating a new OtherClass, you're not providing a method the delegate should "point" to. Therefore, when you're OtherClass calls textToBox(foo); there's no method behind it, and it blows up.


In myClass, you're not calling the overloaded OtherClass constructor that takes a TextToBox, so textToBox(foo) fails because textToBox has not been set.

Can you show the code where myClass is initialized and called?


You should pass in myClass constructor you OtherClass instance created in MainForm, don't create OtherClass instance in myClass it's not the instance to which you attached handler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜