2013-02-27 76 views
6

基本上標題說什麼。 請告訴我(我目前使用第一個)私人EventHandler和私人事件EventHandler之間的區別?

private EventHandler _progressEvent; 

private event EventHandler _progressEvent; 

我有一個方法這兩個之間的差

void Download(string url, EventHandler progressEvent) { 
    doDownload(url) 
    this._progressEvent = progressEvent; 
} 

的doDownload方法將調用

_progressEvent(this, new EventArgs()); 

到目前爲止它工作正常。但我覺得我正在做一些可怕的錯誤。

回答

8

第一個定義了一個委託,第二個定義了一個事件。兩者是相關的,但它們通常使用的方式非常不同。

一般來說,如果您使用的是EventHandlerEventHandler<T>,則表示您使用的是事件。來電者(用於處理進度)通常會認購(未通過委託),如果您擁有訂閱者,則會提出該事件。

如果你想使用更多功能的方法,並傳入一個委託,我會選擇一個更合適的委託使用。在這種情況下,你並不是真的在EventArgs中提供任何信息,所以也許只是使用System.Action會更合適。

這就是說,事件方法在這裏顯示更合適,從所示的小代碼。有關使用事件的詳細信息,請參見C#編程指南中的Events

你的代碼,使用事件,很可能是這個樣子:

// This might make more sense as a delegate with progress information - ie: percent done? 
public event EventHandler ProgressChanged; 

public void Download(string url) 
{ 
    // ... No delegate here... 

當你打電話給你的進步,你會寫:

var handler = this.ProgressChanged; 
if (handler != null) 
    handler(this, EventArgs.Empty); 

這樣做的用戶將它寫成:

yourClass.ProgressChanged += myHandler; 
yourClass.Download(url); 
+0

我想我真的不需要真實的事件,因爲我只會有1個訂閱者,我需要通過周圍的代表。感謝您的迴應。 – 2013-02-27 18:33:03

1

我不認爲兩者有區別。

event關鍵字是一個像私人內部和受保護的訪問修飾符。 它用於限制對組播代表的訪問。

從最明顯的要至少可見我們

public EventHandler _progressEvent; 
//can be assigned to from outside the class (using = and multicast using +=) 
//can be invoked from outside the class 

public event EventHandler _progressEvent; 
//can be bound to from outside the class (using +=) 
//can be invoked from inside the class 

private EventHandler _progressEvent; 
//can be bound from inside the class (using = or +=) 
//can be invoked inside the class 

private event EventHandler _progressEvent; 
//Same as private. given event restricts the use of the delegate from outside 
// the class - i don't see how private is different to private event