繁体   English   中英

私有事件处理程序和私有事件事件处理程序的区别?

[英]Difference between private EventHandler and private event EventHandler?

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

private EventHandler _progressEvent;

private event EventHandler _progressEvent;

我有一个方法

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

doDownload 方法将调用

_progressEvent(this, new EventArgs());

到目前为止,它运行良好。 但我觉得我在做一些非常错误的事情。

第一个定义一个委托,第二个定义一个事件。 这两者是相关的,但它们的使用方式通常非常不同。

通常,如果您使用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://docs.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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM