2010-04-14 26 views
1

我已經創建了一個小應用程序,但我現在想要合併某些類型的可通過列表框查看的日誌記錄。數據的來源可以從任意數量的地方發送。我創建了一個新的日誌類,它將傳入一個委託。我認爲我接近一個解決方案,但我收到一個NullReferenceException,我不知道正確的解決方案。這裏是什麼林試圖做一個例子:使用委託記錄類(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的接收數據,它拋出一個錯誤。任何幫助你可以給予讚賞。

+0

請添加異常文本和調用堆棧 – 2010-04-14 17:45:20

回答

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

對不起,如果我有點新的在這個,但如果我刪除了空的構造函數我怎麼會通過正確的代理從MyClass?它沒有像Form那樣對TextToBox的引用。 – 2010-04-14 18:02:57

+0

@Leroy - MyClass初始化在哪裏? – ChaosPandion 2010-04-14 18:35:49

+0

我希望能夠簡化這個例子中的問題,但是看起來我只是把整個代碼放在了一起。 Form1調用一個API(Class1),該類是MyClass正在初始化的地方。 MyClass接收我想登錄表單的流數據。 – 2010-04-14 20:18:26

1

更改OtherClass檢查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); 
     } 
    } 
} 

現在你雖然得到異常的原因是因爲在你的myClass當你創建一個新的OtherClass時,你沒有提供一個委託人應該「指向」的方法。因此,當你的其他類呼叫textToBox(foo);時,它沒有任何方法,並且它爆炸了。

+0

我覺得如果'textToBox == null'類就處於無效狀態。 – ChaosPandion 2010-04-14 17:54:37

1

您應該在myClass構造函數中傳遞您在MainForm中創建的OtherClass實例,不要在myClass中創建OtherClass實例,它不是您附加處理程序的實例。

1

在myClass中,你沒有調用帶有TextToBox的重載的OtherClass構造函數,所以textToBox(foo)失敗,因爲textToBox尚未設置。

你可以顯示myClass被初始化和調用的代碼嗎?