2011-12-07 14 views
1

我正在創建一個類庫,並在Windows窗體程序中使用它。 我想在程序中處理這個庫的事件。 我使用這個代碼:在類內部引發事件並在另一個類上使用處理函數

類的庫中:

public class KSEDataServIO 
{ 
    public delegate void IsReadyForUseEventHandler(object sender, IsReadyForUseEventArgs e); 
    public event IsReadyForUseEventHandler IsReadyForUse; 
    public KSEDataServIO(){ 
     EvArg = new IsReadyForUseEventArgs("AuthOkay"); 
     IsReadyForUse(this, EvArg); //This is where i get the issue. 
    } 
} 

,並在窗口表我這樣做:

private void button1_Click(object sender, EventArgs e) { 
      KSEDataServIO con = new KSEDataServIO(); 
      con.IsReadyForUse += new KSEDataServIO.IsReadyForUseEventHandler(con_IsReadyForUse); 
} 

void con_IsReadyForUse(object sender, IsReadyForUseEventArgs e) 
{ 
    MessageBox.Show(e.Etat); 
} 

我得到一個NullReferenceException到線'IsReadyForUse(this,EvArg);'在類庫裏面。 有什麼想法?

回答

2

您的問題是您在KSEDataServIO的構造函數中引發事件。此時沒有訂閱該事件處理程序,因此引發空引用異常。

這麼一件事是要適當提高事件處理這種模式常用於其中:

public delegate void IsReadyForUseEventHandler(object sender, IsReadyForUseEventArgs e); 
public event IsReadyForUseEventHandler IsReadyForUse; 

void OnIsReadyForUse(IsReadyForUseEventArgs e) 
{ 
    var handler = IsReadyForUse; 
    if (handler != null) 
    { 
     handler(this, e); 
    } 
} 

然後使用它像這樣引發事件:

OnIsReadyForUse(new IsReadyForUseEventArgs("AuthOkay")) 

其次引發事件在你的構造函數中沒有多少意義,因爲沒有任何東西可能已經訂閱了處理程序(除非你傳遞一個處理程序作爲構造函數參數)。您將需要找到另一個觸發器,以便稍後提出事件。

此外,你應該在你的課堂上暴露IsReady屬性。因此,如果用戶稍後出現,則可以查詢該對象是否已準備就緒。如果IsReady事件在您開始在某處使用該對象時已引發,則您可能會錯過該事件。

編輯:你可以通過一個處理程序的構造,如果你真的想這樣做:

public KSEDataServIO(IsReadyForUseEventHandler handler) 
{ 
    IsReadyForUse += handler; 
    OnIsReadyForUse(new IsReadyForUseEventArgs("AuthOkay")); // see pattern above 
} 

然而,由於您的活動提供this爲你傳遞一個對象的引用它之前發件人完成執行整個構造函數可能導致難以追蹤的問題。如果您唯一要舉辦活動的地方是構造函數的結尾,那麼您並不需要它。

0

在分配con_IsReadyForUse之前,您正在構造函數中引發事件。

相關問題