samedi 3 décembre 2016

Check if a property has a DisplayNameAttribute

I'm trying to verify if a class property has an DisplayNameAttribute. I would like to analise a property and return true or false based on that criteria.

This is what i have so far:

Sample Class:

public class SampleDTO
{
    [DisplayName("Some Display Name")]
    public int propertyA { get; set; }

    public int propertyB { get; set; }
}

Method:

public static DataTable ToDataTable<T>(this List<T> iList)
{
    //(...)


    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(typeof(T));

    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
        Type type = propertyDescriptor.PropertyType;

        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            type = Nullable.GetUnderlyingType(type);


        //check if property has a DisplayNameAttribute
        var att = type.GetCustomAttributes(typeof(DisplayNameAttribute), true);

        //if it has, add to datatable
        if (att != null || !att.Any())
        {
            //add to datatable...
        }

    }


    //(...)
}

My Issue:

//check if property has a DisplayNameAttribute
var att = type.GetCustomAttributes(typeof(DisplayNameAttribute), true);

//if it has, add to datatable
if (att != null || !att.Any())
{
    //add to datatable...
}

So far i'm unable to successfully check if the property has a DisplayNameAttribute.





Aucun commentaire:

Enregistrer un commentaire