2008-10-16 112 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; 
}