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

时间:2008-11-07 19:41:27

标签: 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; }
}

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

[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);
}

两者

property.GetCustomAttributes(true);

Attribute.GetCustomAttributes(property, true);

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

2 个答案:

答案 0 :(得分:2)

object[] SomeMagic (PropertyInfo property)
{
    return property.GetCustomAttributes(true);
}

更新:

由于我的上述答案不起作用,为什么不尝试这样的事情:

public void Should_Use_Magic_To_Get_CustomAttributes_From_Ancestry()
{

    Assert.AreEqual(checkAttributeCount (typeof (Sedan), "TurningRadious"), 3);
}


int checkAttributeCount (Type type, string propertyName)
{
        var attributesCount = 0;

        attributesCount += countAttributes (type, propertyName);
        while (type.BaseType != null)
        {
            type = type.BaseType;
            attributesCount += countAttributes (type, propertyName);
        }

        foreach (var i in type.GetInterfaces ())
            attributesCount += countAttributes (type, propertyName);
        return attributesCount;
}

int countAttributes (Type t, string propertyName)
{
    var property = t.GetProperty (propertyName);
    if (property == null)
        return 0;
    return (property.GetCustomAttributes (false).Length);
}

答案 1 :(得分:1)

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

上的评论