2008-11-07 11 views
5

Donc, si j'ai:Comment obtenir tous les attributs sur l'ancêtre de l'interface/type de base d'une propriété?

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

Quelle magie puis-je utiliser pour faire quelque chose comme:

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

deux

property.GetCustomAttributes(true); 

Et

Attribute.GetCustomAttributes(property, true); 

Renvoie seulement 1 attribut. L'instance est celle créée avec MyCustomAttribute (1). Cela ne semble pas fonctionner comme prévu.

Répondre

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

MISE À JOUR:

Depuis ma réponse ci-dessus ne fonctionne pas pourquoi ne pas essayer quelque chose comme ceci:

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

Dans l'exemple fourni, l'assertion échoue. Il renvoie 1 attribut, pas tous les 3. –

+0

Vous avez raison, c'est parce que c'est juste un attribut personnalisé. – albertein

+0

Si je change l'instance de l'attribut, il semble ne retourner que celui de la voiture. Donc, ce n'est pas la recherche de voiture. Voir la question mise à jour. Ty pour l'aide cependant. –