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) 构建的实例。这似乎没有按预期工作。

4

2 回答 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);
}
于 2008-11-07T19:51:26.513 回答
1

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

于 2009-02-24T10:50:19.977 回答