gpt4 book ai didi

c# - C# 'event' 关键字的多重含义?

转载 作者:可可西里 更新时间:2023-11-01 08:23:32 31 4
gpt4 key购买 nike

我最近重新阅读了 Eric Lippert 的 ridiculously awesome 上的一些旧帖子博客并遇到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.

为了好玩,我的同事和我自问自答,除了其中一个关键字之外,我能够为所有关键字想出至少两种用途。令我难过的是 event

显然,在声明委托(delegate)类型的成员字段时使用 event 会将其转换为事件(例如,仅公开添加/删除运算符)。事件的其他含义是什么?

编辑(答案):

感谢@Hans Passant,我从 C# spec 中挖出了这一点这解释了事件的其他用途——作为事件属性的(默认)属性目标说明符(来自第 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 the event attribute-target-specifier indicates that the attribute applies to the event; the presence of the field attribute-target-specifier indicates that the attribute applies to the field; and the presence of the method attribute-target-specifier indicates that the attribute applies to the methods.

最佳答案

作为属性目标说明符。我想不出你这样做的充分理由:

[AttributeUsage(AttributeTargets.Event)]
class MyAttribute : Attribute { }

class foo {
[event: MyAttribute]
public event EventHandler goo;
}

关于c# - C# 'event' 关键字的多重含义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6670955/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com