如何获取属性接口/基类型继承链上的所有属性?

5

那么,如果我有:

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个回答

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个属性,而不是全部3个。 - Dane O'Connor
你说得对,那是因为它实际上只是一个自定义属性。 - albertein
如果我更改属性的实例,似乎只会返回汽车上的一个。因此它没有在汽车后面搜索。请参见更新的问题。感谢您的帮助。 - Dane O'Connor

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接