【发布时间】:2019-12-08 20:31:35
【问题描述】:
我有以下属性,其中 Inherited 设置为 true。
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Method, Inherited = true)]
public class InheritedAttribute : Attribute { }
DerivedA 类包含一个属性,该属性使用[InheritedAttribute] 标记覆盖 BaseA 的虚拟属性。
public class BaseA
{
[InheritedAttribute]
public virtual int prop { get; set; }
}
public class DerivedA : BaseA
{
public override int prop { get; set; }
}
很遗憾,DerivedA.prop 上没有找到该属性,因此该属性还没有被继承到子属性。
public static void Main()
{
var propertyInfo = typeof(DerivedA).GetProperties()[0];
// propertyInfo.CustomAttributes is empty
// propertyInfo.GetCustomAttributes(true) is empty
}
如果属性被放置在方法而不是属性上,如example code on microsoft's website 中所示,则该属性将按预期继承,并将在methodInfo.CustomAttributes 中找到。
属性继承是不允许的吗?还是我完全错过了其他东西?
【问题讨论】:
-
只是一个想法:属性的某些属性不是在属性级别上实现的,而是在 Getter 和 Setter 级别上实现的。你能检查
propertyInfo.GetGetMethod.GetCustomAttributes(true)。由于这是一种方法,并且方法应该按照描述的方式工作,也许就是这样。 (GetSetMethod 也一样)
标签: c# .net properties