Wie erhalte ich die Instanz Wert einer Immobilie mit einem Attribut gekennzeichnet?
-
03-07-2019 - |
Frage
Ich habe eine Klasse, die mit einem benutzerdefinierten Attribut gekennzeichnet ist, wie folgt aus:
public class OrderLine : Entity
{
...
[Parent]
public Order Order { get; set; }
public Address ShippingAddress{ get; set; }
...
}
Ich möchte eine generische Methode schreiben, wo ich die Immobilie auf einer Entity erhalten müssen, die mit dem Übergeordnetes Attribut gekennzeichnet ist.
Hier ist mein Attribut:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}
Wie schreibe ich das?
Lösung
Mit Type.GetProperties () und 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;
}
Andere Tipps
Dies funktioniert für mich:
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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow