In C #, can an attribute be applied to a static class, method, or property?

Is it possible to apply an attribute to a static class, method or property in C #? How:

[MyAttribute]
public static MyMethods(string str) ...
+5
source share
5 answers

There really are two questions.

Can attributes as a whole be applied to a class, method, or property?

Yes, attributes can target any of these constructs (and many others)

Is it valid for a specific attribute?

It depends on the specific attribute. Attributes can control which constructs they can be applied by enumeration AttributeTargetsand, therefore, make it illegal to apply a particular attribute to a particular construct.

, ParamArrayAttribute , ObsoleteAttribute ( , , , )

+6

, , , .

:

[MyAttribute("hello")]
      public static string SayHello(string str)
      {
         return str;
      }
+2

. . .

, .

+1

, .

+1
0

All Articles