ConditionalAttribute and other special classes

ConditionalAttribute can be used to remove calls using the marked method, depending on specific compiler characters. I assume that we could not create this class ourselves, since the compiler should look for it exactly.

I was wondering if there are other classes that use a compiler or language that we could not program ourselves.

+6
source share
3 answers
  • The compiler searches for [ExtensionAttribute] to specify extension methods (and classes containing extension methods).

  • [DynamicAttribute] used to indicate that an element should be considered as a dynamic type (even if the member type itself is just an object )

  • [InternalsVisibleTo] allows one assembly to access the internal members of another.

Basically look at the System.Runtime.CompilerServices and examine the attributes there ... many of them will be handled specifically by the compiler, even if it is not a C # compiler (for example, DateTimeConstantAttribute not used by the C # compiler, as far as I know, but DecimalConstantAttribute . Maybe that the C # compiler will consume constant DateTime values, although they will not create them ...)

+4
source

in addition to those indicated;

 AttributeUsageAttribute 

has special compiler support as it limits (when compiling) how you can apply attributes

 ObsoleteAttribute 

also used by the compiler for warnings or usage errors.

I suspect, however, that technically you could write all this yourself - as long as you write your own libarary and System.dll; p The compiler usually searches for a template / signature, since it must serve different runtime environments - and you do not have to use the main MS libraries. However, the behavior is determined by the compiler, not the class, so you cannot force it to do something else.

+6
source

[SerializableAttribute] appears on the mind. The compiler handles this differently for other attributes, I believe that it translates to a specific instruction in IL ..

EDIT . As an example, consider IL for ArgumentException, the class definition is as follows:

 .class public auto ansi serializable beforefieldinit ArgumentException 

Note the * 'serializable' modifier. Usually with an attribute you expect to see something like the following, but it is not:

 .custom instance void System.SerializableAttribute::.ctor() = ( 
0
source

Source: https://habr.com/ru/post/890658/


All Articles