获取覆盖属性的属性时有不同的行为吗?
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 调用没有得到结果?
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.
}
Why do I get no result from the first GetCustomAttributes call?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
MemberInfo.GetCustomAttributes 文档(继承到 PropertyInfo)指出;
换句话说,(错误的)行为是设计造成的。
The documentation for MemberInfo.GetCustomAttributes (inherited to PropertyInfo) states;
In other words, (wrong) behavior by design.