samedi 18 mars 2017

Pass property name by lambda expression for reading attribute values

I have found this solution:

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}

Code by jgauffin from How to retrieve Data Annotations from code

I always use the extension this way:

foo.GetAttributeFrom<StringLengthAttribute>(nameof(Foo.Bar)).MaximumLength

Is there a way to pass the propertyName by using a lambda like:

foo.GetAttributeFrom<StringLengthAttribute>(f => f.Bar).MaximumLength

Thank you in advance!





Aucun commentaire:

Enregistrer un commentaire