2008-10-16 4 views
3

У меня есть класс, который помечен пользовательский атрибут, как это:Как получить значение экземпляра свойства, помеченного атрибутом?

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

Я хочу написать универсальный метод, когда мне нужно, чтобы получить собственность на Сущности, помеченный атрибут Parent.

Вот мой Атрибут:

[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

Я не думаю, что будет компилировать. Посмотрите на «как 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; 
} 
Смежные вопросы