考虑到以下情况,我不希望编译器允许从基本属性派生的多个属性(假设它被设置为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
}发布于 2009-10-12 11:24:41
问题很简单,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]。
https://stackoverflow.com/questions/1553986
复制相似问题