C#“事件”的多重含义关键词?
我最近重读了 Eric Lippert 的非常棒博客上的一些旧帖子,并发现这个花絮:
C#的相当一部分关键字被用在两个或多个中 方式:fixed、into、partial、out、in、new、delegate、where、using、 类、结构、true、false、base、this、event、return 和 void all 至少有两种不同的含义。
只是为了好玩,我和我的同事对自己进行了自我测验,除了其中一个关键字之外,我能够为所有关键字想出至少两种用途。令我困惑的是事件
。
显然,在声明委托类型的成员字段时使用event
会将其转换为事件(例如,仅公开添加/删除运算符)。事件的其他含义是什么?
编辑(答案):
感谢@Hans Passant,我从 C# 规范中挖出了这一点 解释了事件的其他用法——作为事件属性的(默认)属性目标说明符(来自第 17.2 节):
在事件声明中指定的省略事件的属性 访问器可以应用于正在声明的事件、关联的事件 字段(如果事件不是抽象的),或关联的添加和 删除方法。在没有属性目标说明符的情况下, 属性适用于事件。
事件的存在
attribute-target-specifier表示该属性适用于 事件;字段
的存在attribute-target-specifier表明 该属性适用于该字段;以及的存在method
attribute-target-specifier 表示该属性适用 到方法。
I was recently re-reading some old posts on Eric Lippert's ridiculously awesome blog and came across this tidbit:
A considerable fraction of the keywords of C# are used in two or more
ways: fixed, into, partial, out, in, new, delegate, where, using,
class, struct, true, false, base, this, event, return and void all
have at least two different meanings.
Just for fun my coworkers and I quizzed ourselves and I was able to come up with at least two uses for all but one of those keywords. The one that stumped me is event
.
Obviously, using event
when declaring a member field of a delegate type turns it into an event (e.g. only add/remove operators are exposed). What's the other meaning of event?
EDIT (Answer):
Thanks to @Hans Passant I dug up this bit out of the C# spec that explains the other use of event -- as (the default) attribute target specifier for attributes on an event (from section 17.2):
An attribute specified on an event declaration that omits event
accessors can apply to the event being declared, to the associated
field (if the event is not abstract), or to the associated add and
remove methods. In the absence of an attribute-target-specifier, the
attribute applies to the event. The presence of theevent
attribute-target-specifier indicates that the attribute applies to the
event; the presence of thefield
attribute-target-specifier indicates
that the attribute applies to the field; and the presence of themethod
attribute-target-specifier indicates that the attribute applies
to the methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
作为属性目标说明符。我想不出你这样做的充分理由:
As the attribute target specifier. I can't think of a good reason you would do this:
有两种方法可以使用
事件
,但我不确定这是否符合条件。There are two ways to use
event
but I'm not sure if that qualifies.来自MSDN,两种方法使用事件是:
[attributes] [modifiers] 事件类型声明符;
[attributes] [modifiers] 事件类型成员名称{访问器声明};
From MSDN, the two ways to use event are:
[attributes] [modifiers] event type declarator;
[attributes] [modifiers] event type member-name {accessor-declarations};