C # Attributes and attribute location / goals

I read about attributes and understand that they can be applied to various targets with code - (see Attributes of Attributes ).

So, looking at the AssemblyInfo.cs file in my project, I see the following:

[assembly: AssemblyTitle("AttributesDemo")] [assembly: AssemblyDescription("")] 

That makes sense to me. The attribute whose purpose is the assembly.

In my code, I can add an attribute to the class as follows:

 [MyAttribute] class MySerialzableClass { 

With MyAttribute will be:

 [AttributeUsage (AttributeTargets.All)] public class MyAttribute : System.Attribute { } 

So, I thought of the assembly: instruction in the first block of code. And tried this, just for experimentation:

 [class: MyAttribute] class MySerialzableClass { 

This gives a compiler warning:

'class' is not a recognized attribute of a location. All attributes in this block will be ignored.

So my question is this: why do I need to specify a Target Attribute Target for some attributes and are not required for others? Moreover, why should you do this?

+4
source share
3 answers

you need to explicitly indicate the goal in case the goal is not represented in the code. I know only three goals, assembly, module and return:

 [return: MyAttribute] public static int meth( 

for a class defining a class: excessive, the compiler can understand what you meant

+5
source

You can specify target attributes for any use of attributes, but only those that do not have a default value ( assembly and module ) are required. In addition, you must use these annotations if you want to apply the attribute to a target other than the default.

Non-default goal examples:

 [return: MyAttribute] public int Method() { ... } public int Property { get; [param: MyAttribute] // applies to the parameter to the setter set; } 

In your example, the correct target (default) is type :

 [type: MyAttribute] class MySerialzableClass { } 
+4
source

Typically, an attribute appears right before it affects, for example, a class or method. There is no "earlier" for attributes of the entire assembly, so you need to specify.

+3
source

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


All Articles