【问题标题】:Honouring of AttributeUsage on derived attribute types在派生属性类型上尊重 AttributeUsage
【发布时间】:2009-10-12 11:13:49
【问题描述】:

鉴于以下情况,如果设置为 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
    }

【问题讨论】:

    标签: c# inheritance attributes allowmultiple


    【解决方案1】:

    问题很简单,AllowMultiple 检查只比较相同实际 类型的属性(即实例化的具体类型) - 出于这个原因,可能最好与sealed 属性一起使用。

    例如,它将强制执行以下内容(作为非法副本),继承自 BaseAttribute

    [DerivedAttributeB()]
    [DerivedAttributeB()]
    public string Name { get; set; }
    

    简而言之,我不认为你可以在这里做你想做的事...(对每个属性强制执行不超过一个实例包括BaseAttribute 的子类)。

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

    [Description("abc")]
    [I18NDescriptionAttribute("abc")]
    public string Name { get; set; }
    
    class I18NDescriptionAttribute : DescriptionAttribute {
        public I18NDescriptionAttribute(string resxKey) : base(resxKey) { } 
    }
    

    上面的意图是在运行时从 resx 提供一个[Description]ComponentModel 等完全支持) - 但它不能阻止你也添加一个 [Description]

    【讨论】:

    • 我担心可能是这种情况,谢谢您的确认。
    猜你喜欢
    • 2016-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    相关资源
    最近更新 更多