2008-11-07 21 views
5

Vì vậy, nếu tôi có:Làm cách nào để có được tất cả các thuộc tính trên giao diện của một thuộc tính/tổ tiên cơ sở?

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

kỳ diệu Những gì tôi có thể sử dụng để làm một cái gì đó như:

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

Cả

property.GetCustomAttributes(true); 

Attribute.GetCustomAttributes(property, true); 

Chỉ trả về 1 thuộc tính. Ví dụ là phiên bản được xây dựng với MyCustomAttribute (1). Điều này dường như không hoạt động như mong đợi.

Trả lời

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

UPDATE:

Từ câu trả lời trên của tôi không hoạt động tại sao không thử một cái gì đó như thế này:

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

Trong ví dụ được cung cấp, xác nhận không thành công. Nó trả về 1 thuộc tính, không phải tất cả 3. –

+0

Bạn nói đúng, đó là bởi vì nó thực sự chỉ là một tùy chỉnh. – albertein

+0

Nếu tôi thay đổi thể hiện của thuộc tính, nó dường như chỉ trả về một chiếc xe hơi. Vì vậy, nó không tìm kiếm sau khi xe. Xem câu hỏi được cập nhật. Ty cho sự giúp đỡ mặc dù. –

Các vấn đề liên quan