2008-10-16 362 views
3

我有一個標有一個自定義屬性,像這樣一類:如何獲取標有屬性的屬性的實例值?

public class OrderLine : Entity 
{ 
    ... 
    [Parent] 
    public Order Order { get; set; } 
    public Address ShippingAddress{ get; set; } 
    ... 
} 

我想編寫一個通用的方法,在這裏我需要得到其上標有父屬性的實體屬性。

這裏是我的屬性:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] 
public class ParentAttribute : Attribute 
{ 
} 

我怎麼寫?

回答

3

使用Type.GetProperties()和PropertyInfo.GetValue()

T GetPropertyValue<T>(object o) 
    { 
     T value = default(T); 

     foreach (System.Reflection.PropertyInfo prop in o.GetType().GetProperties()) 
     { 
      object[] attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false); 
      if (attrs.Length > 0) 
      { 
       value = (T)prop.GetValue(o, null); 
       break; 
      } 
     } 

     return value; 
    } 
+0

我不認爲這會編譯。看看'as T'。 – leppie 2008-10-16 13:43:20

2

這個工作對我來說:

public static object GetParentValue<T>(T obj) { 
    Type t = obj.GetType(); 
    foreach (var prop in t.GetProperties()) { 
     var attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false); 
     if (attrs.Length != 0) 
      return prop.GetValue(obj, null); 
    } 

    return null; 
}