Как получить все атрибуты в интерфейсе свойства / происхождении базового типа? - PullRequest
5 голосов
/ 07 ноября 2008

Итак, если у меня есть:

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 голосов
/ 07 ноября 2008
object[] SomeMagic (PropertyInfo property)
{
    return property.GetCustomAttributes(true);
}

UPDATE:

Так как мой ответ выше не работает, почему бы не попробовать что-то вроде этого:

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 голос
/ 24 февраля 2009

это проблема фреймворка. Атрибуты интерфейса игнорируются GetCustomAttributes. см. комментарий к этому сообщению в блоге http://hyperthink.net/blog/getcustomattributes-gotcha/#comment-65

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...