2008-11-07 1 views
5

Так что, если у меня есть:Как получить все атрибуты на основе интерфейса/basetype свойства?

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
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); 
} 
+0

В приведенном примере утверждение терпит неудачу. Он возвращает 1 атрибут, а не все 3. – 2008-11-07 19:52:12

Смежные вопросы