我正在使用从属性类继承的自定义属性.我这样使用它:
[MyCustomAttribute("CONTROL")]
[MyCustomAttribute("ALT")]
[MyCustomAttribute("SHIFT")]
[MyCustomAttribute("D")]
public void setColor()
{
}
Run Code Online (Sandbox Code Playgroud)
但是显示了"Duplicate'MyCustomAttribute'属性"错误.
如何创建重复的允许属性?
Ant*_*lev 171
将AttributeUsage
属性粘贴到您的Attribute类(是的,那是满口)并设置AllowMultiple
为true
:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public sealed class MyCustomAttribute: Attribute
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 19
AttributeUsageAttribute ;-p
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class MyAttribute : Attribute
{}
Run Code Online (Sandbox Code Playgroud)
但请注意,如果您使用的是ComponentModel(TypeDescriptor
),则每个成员仅支持一个属性实例(每个属性类型); 原始反射支持任何数字......
默认情况下,Attribute
s仅限于一次应用于单个字段/属性/等。您可以从MSDN 上的Attribute
类定义中看到以下内容:
[AttributeUsageAttribute(..., AllowMultiple = false)]
public abstract class Attribute : _Attribute
Run Code Online (Sandbox Code Playgroud)
因此,正如其他人指出的那样,所有子类都以相同的方式受到限制,并且如果您需要同一属性的多个实例,则需要显式设置AllowMultiple
为true
:
[AttributeUsage(..., AllowMultiple = true)]
public class MyCustomAttribute : Attribute
Run Code Online (Sandbox Code Playgroud)
在允许多种用途的属性上,您还应该覆盖TypeId
属性以确保诸如PropertyDescriptor.Attributes
预期的属性能够正常工作。最简单的方法是实现该属性以返回属性实例本身:
[AttributeUsage(..., AllowMultiple = true)]
public class MyCustomAttribute : Attribute
{
public override object TypeId
{
get
{
return this;
}
}
}
Run Code Online (Sandbox Code Playgroud)
(发布此答案不是因为其他答案是错误的,而是因为这是更全面/规范的答案。)