2008-11-07 9 views
5

Yani, varsa:Bir mülkün arayüzü/taban tipi atalarından tüm öznitelikler nasıl edinilebilir?

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; } 
} 
ben böyle bir şey yapmak için kullanabileceği sihir nedir

:

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

İkisi

property.GetCustomAttributes(true); 

Ve

Attribute.GetCustomAttributes(property, true); 

Sadece 1 özniteliği döndür. Örnek, MyCustomAttribute (1) ile oluşturulmuş olanıdır. Bu beklendiği gibi çalışmıyor.

cevap

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

GÜNCELLEME:

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

Sağlanan örnekte, onaylama başarısız olur. Tüm 3 değil, 1 özniteliği döndürür. –

+0

Haklısınız, çünkü bu gerçekten sadece bir özel atıftır. – albertein

+0

Özniteliğin örneğini değiştirirsem, yalnızca arabayı geri döndürüyor gibi görünüyor. Yani arabanın peşinden gitmiyor. Güncellenmiş soruya bakın. Yardım için Ty olsa. –