C# 尊重派生属性类型的属性设置
鉴于以下情况,我不希望编译器允许从基属性派生的多个属性,因为该属性设置为AllowMultiple=false。事实上,它编译起来没有问题——我在这里遗漏了什么C# 尊重派生属性类型的属性设置,c#,inheritance,attributes,allowmultiple,C#,Inheritance,Attributes,Allowmultiple,鉴于以下情况,我不希望编译器允许从基属性派生的多个属性,因为该属性设置为AllowMultiple=false。事实上,它编译起来没有问题——我在这里遗漏了什么 using System; [AttributeUsage(AttributeTargets.Property,AllowMultiple=false,Inherited=true)] abstract class BaseAttribute : Attribute { } sealed class DerivedAttribute
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
}
问题很简单,
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]
(完全由组件模型
等支持)-但它不能阻止您也添加[Description],我担心可能是这样,感谢您的确认。