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 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.
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};
精彩评论