Come ottengo il valore dell'istanza di una proprietà contrassegnata con un attributo?
-
03-07-2019 - |
Domanda
Ho una classe contrassegnata da un attributo personalizzato, come questa:
public class OrderLine : Entity
{
...
[Parent]
public Order Order { get; set; }
public Address ShippingAddress{ get; set; }
...
}
Voglio scrivere un metodo generico, in cui devo ottenere la proprietà su un'entità contrassegnata con l'attributo Parent.
Ecco il mio attributo:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}
Come scrivo questo?
Soluzione
Usa Type.GetProperties () e 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;
}
Altri suggerimenti
Questo funziona per me:
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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow