开发者

Multiple meanings of the C# 'event' keyword?

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 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.


As the attribute target specifier. I can't think of a good reason you would do this:

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

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


There are two ways to use event but I'm not sure if that qualifies.

public event MyDelegate MyEvent;

public event MyDelegate MyEvent
{
    add { ... }
    remove { ... }
}


From MSDN, the two ways to use event are:

[attributes] [modifiers] event type declarator;

[attributes] [modifiers] event type member-name {accessor-declarations};

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜