Как получить значение экземпляра свойства, отмеченного атрибутом?

StackOverflow https://stackoverflow.com/questions/208570

  •  03-07-2019
  •  | 
  •  

Вопрос

У меня есть класс, помеченный настраиваемым атрибутом, например:

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

Я хочу написать общий метод, в котором мне нужно получить свойство объекта, помеченное атрибутом Parent.

Вот мой атрибут:

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

Как мне это написать?

Это было полезно?

Решение

Используйте Type.GetProperties() и 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;
    }

Другие советы

Это работает для меня:

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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top