如何在属性的接口/ basetype祖先上获取所有属性?

Dan*_*nor 5 c# reflection attributes

所以,如果我有:

public class Sedan : Car 
{
    /// ...
}

public class Car : Vehicle, ITurn
{
    [MyCustomAttribute(1)]
    public int TurningRadius { get; set; }
}

public abstract class Vehicle : ITurn
{
    [MyCustomAttribute(2)]
    public int TurningRadius { get; set; }
}

public interface ITurn
{
    [MyCustomAttribute(3)]
    int TurningRadius { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我可以使用什么魔法来做类似的事情:

[Test]
public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{
    var property = typeof(Sedan).GetProperty("TurningRadius");

    var attributes = SomeMagic(property);

    Assert.AreEqual(attributes.Count, 3);
}
Run Code Online (Sandbox Code Playgroud)

property.GetCustomAttributes(true);
Run Code Online (Sandbox Code Playgroud)

Attribute.GetCustomAttributes(property, true);
Run Code Online (Sandbox Code Playgroud)

只返回1个属性.该实例是使用MyCustomAttribute(1)构建的实例.这似乎没有按预期工作.

Dam*_*ern 1

这是一个框架问题。GetCustomAttributes 会忽略接口属性。请参阅此博客文章的评论http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65