简体   繁体   English

事件处理程序访问器/属性的确切用途是什么?

[英]What exactly is the use of event handler accessors/properties?

I have an interface with the line: 我有一行接口:

event EventHandler<MagazineEventArgs> MagazineChangedEvent;

When I implement the interface, Visual Studio generates the following template for me: 当我实现接口时,Visual Studio会为我生成以下模板:

event EventHandler<MagazineEventArgs> IMagazineConfigView.MagazineChangedEvent
{
     add { throw new NotImplementedException(); }
     remove { throw new NotImplementedException(); }
}

However, I don't understand how exactly I should make use of these properties. 但是,我不知道我应该如何充分利用这些属性。

Often, you can just use a field-like event , eg just declare: 通常,您可以只使用类似字段的事件 ,例如,只需声明:

public event EventHandler<MagazineEventArgs> MagazineChangedEvent;

That's roughly equivalent to declaring a private delegate field and accessors which subscribe to it and unsubscribe from it: 大致等于声明一个私有委托字段和订阅者并取消订阅的访问者:

private EventHandler<MagazineEventArgs> magazineChanged;

public event EventHandler<MagazineEventArgs> MagazineChangedEvent
{
    add { magazineChanged += value; }
    remove { magazineChanged -= value; }
}

... but the field-like event syntax provides some more thread safety. ...但是类字段事件语法提供了更多的线程安全性。 The exact nature of that thread safety depends on the version of C# you're using. 线程安全性的确切性质取决于您使用的C#版本。 From C# 4 onwards, they're a bit cleaner than they were - see the blog posts of Chris Burrows for more details ( part 1 , part 2 , part 3 , afterword ). 从C#4开始,它们比以前更加干净-有关更多详细信息,请参阅Chris Burrows的博客文章( 第1 部分第2 部分第3部分后记 )。

You typically only need to implement the event yourself if you're doing something rather different - for example, chaining event subscription to a different underlying event, or to use EventHandlerList as a way of efficiently storing sparse subscriptions for a wide range of events. 通常,您只需要在做一些完全不同的事情时自己实现事件即可-例如,将事件订阅链接到另一个基础事件,或者使用EventHandlerList作为有效地存储各种事件的稀疏订阅的方式。

It's important to understand how events and plain delegate fields differ - it's similar to the difference between properties and fields, although slightly more nuanced as events only have "subscribe and unsubscribe" operations, with no way of the caller raising them or determining other subscribers. 了解事件和普通委托字段之间的区别非常重要-类似于属性和字段之间的区别,尽管由于事件仅具有“订阅和取消订阅”操作,而调用者无法提出它们或确定其他订户的方式,所以它的细微差别会更大。 See my article on the topic for more information. 有关更多信息,请参见我关于该主题的文章

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

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