在派生属性类型上表彰AttributeUsage

Gar*_*h D 5 c# inheritance attributes allowmultiple

鉴于以下情况,我不希望编译器允许从base属性派生的多个属性,因为它们设置为AllowMultiple = false.事实上它编译没有问题 - 我在这里缺少什么?

using System;

[AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=true)]
abstract class BaseAttribute : Attribute { }

sealed class DerivedAttributeA : BaseAttribute { }

sealed class DerivedAttributeB : BaseAttribute { }

    class Sample1
    {
        [DerivedAttributeA()]
        [DerivedAttributeB()]
        public string PropertyA{ get; set; } // allowed, concrete classes differ

        [DerivedAttributeA()]
        [DerivedAttributeA()]
        public string PropertyB { get; set; } // not allowed, concrete classes the same, honours AllowMultiple=false on BaseAttribute
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

问题只是AllowMultiple检查只比较了相同实际类型的属性(即实例化的具体类型) - 并且sealed由于这个原因,最好与属性一起使用.

例如,它将强制执行以下操作(作为非法复制),继承自BaseAttribute:

[DerivedAttributeB()]
[DerivedAttributeB()]
public string Name { get; set; }
Run Code Online (Sandbox Code Playgroud)

总之,我不认为你可以做你想要的这里...(执行不超过一个实例包括子类BaseAttribute每个属性).

这个问题的一个类似例子是:

[Description("abc")]
[I18NDescriptionAttribute("abc")]
public string Name { get; set; }

class I18NDescriptionAttribute : DescriptionAttribute {
    public I18NDescriptionAttribute(string resxKey) : base(resxKey) { } 
}
Run Code Online (Sandbox Code Playgroud)

上面的意图是[Description]在运行时提供一个来自resx(完全支持ComponentModel等) - 但它也无法阻止你添加一个[Description].