How to get the value of an instance of a property marked with an attribute?

I have a class that is marked with a special attribute, for example:

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

I want to write a general method where I need to get a property in an entity that is marked with a parent attribute.

Here is my attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}

How do I write this?

+3
source share
2 answers

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;
    }
+3
source

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;
}
+2
source

Source: https://habr.com/ru/post/1698347/


All Articles