获取重写属性的属性时的行为不同?
问题描述:
using System;
class Program
{
static void Main()
{
var p = typeof(MyClass2).GetProperty("Value");
var a = Attribute.GetCustomAttribute(p, typeof(ObsoleteAttribute), true);
Console.WriteLine(a != null);
}
}
public class MyClass
{
[CommandProperty()]
public virtual string Value { get; set; }
}
public class MyClass2 : MyClass
{
public override string Value { get; set; }
}
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
public class CommandPropertyAttribute : Attribute
{
/* ... */
}
PropertyInfo prop = ***The PropertyInfo of MyClass2.Value***;
object[] attrs = prop.GetCustomAttributes(typeofCPA, true);
Attribute at =Attribute.GetCustomAttribute(prop, typeofCPA, true);
if (attrs.Length == 0 && at != null)
{
// Yes this happens.
}
为什么我从第一次GetCustomAttributes调用没有结果?获取重写属性的属性时的行为不同?
答
documentation for MemberInfo.GetCustomAttributes(继承PropertyInfo)的状态;
此方法忽略属性和事件的继承参数。 要在继承链中搜索属性和 事件的属性,请使用Attribute.GetCustomAttributes方法的相应超载。
换句话说,(设计错误)行为。
+0
此外,我发现此: 继承 - 类型:System.Boolean - 真正的搜索此成员的继承链来查找属性;否则,是错误的。 **该属性和事件被忽略;见备注** - 谢谢 – Tarion 2012-02-20 12:05:50
按照这个例子有困难。 //不会发生什么?定义了“ObsoleteAttribute”的方法? – 2012-02-19 22:32:38
所以要更清楚一点,看起来问题是在重写的成员上找到定义的属性。我假设你想要在继承层次结构中的任何地方返回该成员上定义的属性。 – Reddog 2012-02-19 22:35:20