How to create duplicate allowed attributes

前端 未结 6 1822
旧巷少年郎
旧巷少年郎 2021-02-02 04:58

I\'m using a custom attribute inherited from an attribute class. I\'m using it like this:

[MyCustomAttribute(\"CONTROL\")]
[MyCustomAttribute(\"ALT\")]
[MyCustom         


        
6条回答
  •  旧时难觅i
    2021-02-02 05:18

    By default, Attributes are limited to being applied only once to a single field/property/etc. You can see this from the definition of the Attribute class on MSDN:

    [AttributeUsageAttribute(..., AllowMultiple = false)]
    public abstract class Attribute : _Attribute
    

    Therefore, as others have noted, all subclasses are limited in the same way, and should you require multiple instances of the same attribute, you need to explicitly set AllowMultiple to true:

    [AttributeUsage(..., AllowMultiple = true)]
    public class MyCustomAttribute : Attribute
    

    On attributes that allow multiple usages, you should also override the TypeId property to ensure that properties such as PropertyDescriptor.Attributes work as expected. The easiest way to do this is to implement that property to return the attribute instance itself:

    [AttributeUsage(..., AllowMultiple = true)]
    public class MyCustomAttribute : Attribute
    {
        public override object TypeId
        {
            get
            {
                return this;
            }
        }
    }
    

    (Posting this answer not because the others are wrong, but because this is a more comprehensive/canonical answer.)

提交回复
热议问题