¿Cómo obtengo el valor de instancia de una propiedad marcada con un atributo?
-
03-07-2019 - |
Pregunta
Tengo una clase que está marcada con un atributo personalizado, como este:
public class OrderLine : Entity
{
...
[Parent]
public Order Order { get; set; }
public Address ShippingAddress{ get; set; }
...
}
Quiero escribir un método genérico, donde necesito obtener la Propiedad en una Entidad que está marcada con el atributo de Padres.
Aquí está mi atributo:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}
¿Cómo escribo esto?
Solución
Use Type.GetProperties () y 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;
}
Otros consejos
Esto funciona para mí:
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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow