private EventHandler和private event EventHandler之间的区别是什么?

6
基本上,标题已经表述清楚了。 这两者有什么区别(我目前正在使用第一个)
private EventHandler _progressEvent;

并且

private event EventHandler _progressEvent;

我有一个方法

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

doDownload方法将调用
_progressEvent(this, new EventArgs());

目前为止,它运行良好。但我感觉自己做错了什么。

2个回答

8
第一个定义了一个委托,第二个定义了一个事件。它们之间有关联,但通常使用方式不同。
一般来说,如果您使用的是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);

我想我实际上不需要真正的事件,因为我只有一个订阅者,并且我需要传递委托。感谢您的回复。 - Carlos Magno Rosa

5
对于private,两者之间没有区别,但对于public,您需要使用eventevent关键字是像privateinternalprotected这样的访问修饰符。 它用于限制对多路广播委托的访问。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

1
请注意!订阅的线程安全性有重要区别。请参见 https://dotnetfiddle.net/Wo4lTd。 - Jan
在我看来,这是一个更好的答案。 - Efreeto

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接