AttributeUsage中的多个AttributeTargets

Sea*_* C. 11 c# reflection attributes

[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
...
}
Run Code Online (Sandbox Code Playgroud)

我想在同时使用这个自定义属性的属性的Fileds而不是其他.如何分配多个目标(AttributeTargets.PropertyAttributeTargets.Field)?或者这是不可能的?

AttributeTargets.All这不是我想要的.

Gra*_*ICA 23

您可以使用|(按位OR)运算符指定多个枚举值,从而指定多个这样的目标:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class MyAttribute : Attribute
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

按位OR运算符与AttributeTargets枚举一起使用,因为它的值以特定方式分配,并使用Flags属性标记.

如果您愿意,可以在这里阅读更多内容: