私有事件eventandler和私有事件eventandler的区别

本文关键字:事件 eventandler 区别 | 更新日期: 2023-09-27 18:01:30

基本上就是标题所说的。这两者的区别是什么(我现在用的是第一个)

private EventHandler _progressEvent;

private event EventHandler _progressEvent;

我有一个方法

void Download(string url, EventHandler progressEvent) {
    doDownload(url)
    this._progressEvent = progressEvent;
}
doDownload方法会调用
_progressEvent(this, new EventArgs());
到目前为止,它工作得很好。但是我觉得我做错了什么。

私有事件eventandler和私有事件eventandler的区别

第一个定义委托,第二个定义事件。

一般来说,如果您使用EventHandlerEventHandler<T>,这将表明您正在使用事件。调用者(用于处理进度)通常会订阅事件(而不是在委托中传递),如果您有订阅者,则会引发事件。

如果你想使用更实用的方法,并传递一个委托,我会选择一个更合适的委托来使用。在这种情况下,您并没有真正在EventArgs中提供任何信息,因此可能只使用System.Action会更合适。

话虽如此,从所示的小代码来看,事件方法在这里似乎更合适。有关使用事件的详细信息,请参见c#编程指南中的事件。

你的代码,使用事件,可能看起来像这样:
// 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);

对于private,两者之间没有区别,但对于public,您将希望使用event

event关键字是一个访问修饰符,类似于private internal和protected。它用于限制对多播委托的访问。https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/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 +=), but can't be assigned (using =)
//can only 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