Como faço para obter o valor de instância de uma propriedade marcada com um atributo?

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

  •  03-07-2019
  •  | 
  •  

Pergunta

Eu tenho uma classe que está marcado com um atributo personalizado, como este:

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

Eu quero escrever um método genérico, onde eu preciso para obter a propriedade de uma entidade que está marcado com o atributo Parent.

Aqui está o meu atributo:

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

Como faço para escrever isso?

Foi útil?

Solução

Use 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;
    }

Outras dicas

Isso funciona para mim:

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;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top