ConditionalAttribute and other special classes

若如初见. 提交于 2019-12-05 07:54:03
  • 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 be object)

  • [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...)

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.

[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() = (
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!