如何获取属性覆盖属性?
不起作用 Attribute.GetCustomAttribute:
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
{
[Obsolete]
public virtual string Value { get; set; }
}
public class MyClass2 : MyClass
{
public override string Value { get; set; }
}
输出:False
为什么?
Does not work Attribute.GetCustomAttribute:
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
{
[Obsolete]
public virtual string Value { get; set; }
}
public class MyClass2 : MyClass
{
public override string Value { get; set; }
}
Output: False
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您查看
ObsoleteAttribute
你会看到它的AttributeUsage
设置继承
为 false - 所以属性不会被重写成员继承。我怀疑如果您检查它是否覆盖了基本属性并沿着继承链向上移动,您将能够以这种方式发现该属性。诚然,做这种事情有点混乱。
If you look at the docs for
ObsoleteAttribute
you'll see that itsAttributeUsage
setsInherited
to false - so the attribute isn't inherited by overriding members.I suspect if you check that it's overriding a base property and work your way up the inheritance chain, you'll be able to discover the attribute that way. It's a bit of a mess doing this sort of thing, admittedly.