1

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

这是我到目前为止所拥有的:

样本类:

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。

4

1 回答 1

2
 var t = typeof(SampleDTO);
 var pi = t.GetProperty("PropertyA");
 var hasAttr = Attribute.IsDefined(pi, typeof(DisplayName));
于 2016-12-03T18:34:45.777 回答