简体   繁体   English

在C#中,属性可以应用于静态类,方法还是属性?

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

Can an attribute be applied to a static class, method or property in c#? 可以将属性应用于c#中的静态类,方法或属性吗? Like: 喜欢:

[MyAttribute]
public static MyMethods(string str) ...

There are really two questions here 这里真的有两个问题

Is it possible for attributes in general to be applied to class, method's or properties? 通常可以将属性应用于类,方法或属性吗?

Yes attributes can validly target any of these constructs (and many others) 是属性可以有效地针对任何这些结构(以及许多其他)

Is it valid for a specific attribute to do so? 是否对特定属性有效?

That depends on the specific attribute. 这取决于具体的属性。 Attributes can control which constructs they can be applied to via the AttributeTargets enum and hence make it illegal for a specific attribute to be applied to a specific construct. 属性可以通过AttributeTargets枚举控制它们可以应用于哪些构造,因此将特定属性应用于特定构造是非法的。

For example the ParamArrayAttribute can only target parameters while the ObsoleteAttribute can target pretty much anything (except assemblies and maybe one other I'm missing) 例如, ParamArrayAttribute只能定位参数,而ObsoleteAttribute几乎可以定位任何东西(除了程序集,可能还有一个我缺少的)

Yes you can apply attribute to static class,method,property. 是的,您可以将属性应用于静态类,方法,属性。

example: 例:

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

Yes. 是。 Probably. 大概。 Just try and see. 试着看看。

I wonder why you'd doubt it. 我想知道你为什么怀疑它。

是的,它可以应用。

It depends on the Attribute if it can apply to a static class. 如果它可以应用于静态类,它取决于属性。 Check out AttributeTarget . 查看AttributeTarget As such it is perfectly legal and allowed to decorate a static class or methods to with Attributes. 因此,它是完全合法的,并允许使用Attributes修饰静态类或方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM