检查属性是否具有DisplayNameAttribute

时间:2016-12-03 18:26:06

标签: c# asp.net asp.net-mvc reflection displayname-attribute

我正在尝试验证类属性是否具有DisplayNameAttribute。我想分析一个属性并根据该标准返回true或false。

这是我到目前为止所做的:

样本类:

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

    public int propertyB { get; set; }
}

方式:

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...
        }

    }


    //(...)
}

我的问题:

//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...
}

到目前为止,我无法成功检查该属性是否具有DisplayNameAttribute。

1 个答案:

答案 0 :(得分:1)

 var t = typeof(SampleDTO);
 var pi = t.GetProperty("PropertyA");
 var hasAttr = Attribute.IsDefined(pi, typeof(DisplayName));