Comment obtenir la valeur d'instance d'une propriété marquée avec un attribut?

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

  •  03-07-2019
  •  | 
  •  

Question

J'ai une classe qui est marquée avec un attribut personnalisé, comme ceci:

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

Je veux écrire une méthode générique, où je dois obtenir la propriété sur une entité qui est marquée avec l'attribut Parent.

Voici mon attribut:

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

Comment puis-je écrire cela?

Était-ce utile?

La solution

Utilisez Type.GetProperties () et 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;
    }

Autres conseils

Cela fonctionne pour moi:

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top