私有EventHandler和私有事件EventHandler之间的区别?

Car*_*osa 6 .net c# events delegates event-handling

基本上标题是什么.这两者之间有什么区别(我目前正在使用第一个)

private EventHandler _progressEvent;
Run Code Online (Sandbox Code Playgroud)

private event EventHandler _progressEvent;
Run Code Online (Sandbox Code Playgroud)

我有一个方法

void Download(string url, EventHandler progressEvent) {
    doDownload(url)
    this._progressEvent = progressEvent;
}
Run Code Online (Sandbox Code Playgroud)

doDownload方法会调用

_progressEvent(this, new EventArgs());
Run Code Online (Sandbox Code Playgroud)

到目前为止,它工作正常.但我觉得我做的事情非常糟糕.

Ree*_*sey 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...
Run Code Online (Sandbox Code Playgroud)

当你打电话给你的进度时,你会写:

var handler = this.ProgressChanged;
if (handler != null)
    handler(this, EventArgs.Empty);
Run Code Online (Sandbox Code Playgroud)

这个用户会把它写成:

yourClass.ProgressChanged += myHandler;
yourClass.Download(url);
Run Code Online (Sandbox Code Playgroud)


tim*_*thy 5

对于private,两者之间没有区别,但是对于public您会想要使用event

event 关键字是一个访问修饰符,如 private inside 和 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
Run Code Online (Sandbox Code Playgroud)