How do I get the instance value of a property marked with a Attribute?
-
03-07-2019 - |
Question
I have a class which is marked with a custom attribute, like this:
public class OrderLine : Entity
{
...
[Parent]
public Order Order { get; set; }
public Address ShippingAddress{ get; set; }
...
}
I want to write a generic method, where I need to get the Property on a Entity which is marked with the Parent attribute.
Here is my Attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}
How do I write this?
Solution
Use Type.GetProperties() and 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;
}
OTHER TIPS
This works for 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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow