【问题标题】:How to get the attributes override properties?如何获取属性覆盖属性?
【发布时间】:2011-11-06 13:23:52
【问题描述】:

不起作用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; }
}

输出:假

为什么?

【问题讨论】:

  • 获取属性的时候把MyClass2改成MyClass会怎样?
  • 在这种情况下工作正常。

标签: .net reflection attributes properties virtual


【解决方案1】:

如果您查看 ObsoleteAttribute 的文档,您会发现其 AttributeUsageInherited 设置为 false - 因此该属性不会被覆盖成员继承。

我怀疑如果您检查它是否覆盖了基本属性并沿着继承链向上工作,您将能够以这种方式发现属性。诚然,做这种事情有点乱。

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    相关资源
    最近更新 更多