问题
The ConditionalAttribute
can be used to remove calls to a marked method depending on the compiler symbols defined. I'm assuming we could not create this class ourselves since the compiler must be looking for it specifically.
I was wondering what other classes there are that the compiler, or language uses that we could not code ourselves.
回答1:
The compiler looks for [ExtensionAttribute] to indicate extension methods (and classes containing extension methods).
[DynamicAttribute] is used to indicate that a member should be treated as type
dynamic
(even though the member type itself will just beobject
)[InternalsVisibleTo] allows one assembly to access the internal members of another.
Basically look through the System.Runtime.CompilerServices namespace, and examine the attributes in there... many of them will be handled specially by a compiler, even if it's not the C# compiler (e.g. DateTimeConstantAttribute isn't used by the C# compiler as far as I'm aware, but DecimalConstantAttribute is. It's possible that the C# compiler will consume constant DateTime
values even though it won't produce them...)
回答2:
in addition to those mentioned;
AttributeUsageAttribute
has special compiler support, since it restricts (at compile) how you can apply attributes
ObsoleteAttribute
is also used by the compiler to warn or error about usage.
I suspect though, that technically you could write all of these yourself - as long as you write your own core libarary and System.dll ;p The compiler is generally looking for a pattern/signature, since it must cater for different runtimes - and indeed you don't have to use the MS core libraries. The behaviour, however, is defined by the compiler, not the class - so you can't make it do anything different.
回答3:
[SerializableAttribute] springs to mind. The compiler handles this differently to other attributes, I believe it's translated to a specific instruction in IL..
EDIT Looking at the IL for ArgumentException as an example, the class definition looks like this:
.class public auto ansi serializable beforefieldinit ArgumentException
Note the *'serializable' modifier. Usually with an attribute you would expect to see something like the following, but it is not there:
.custom instance void System.SerializableAttribute::.ctor() = (
来源:https://stackoverflow.com/questions/6368731/conditionalattribute-and-other-special-classes