2016-12-03 86 views
1

我想验证一个类属性是否具有DisplayNameAttribute。我想分析一个属性,并根据该标准返回true或false。检查属性是否具有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。

回答

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

正确的概念,而是更符合OP的问题,他只是需要更换'VAR ATT = type.GetCustomAttributes(typeof运算(DisplayNameAttribute),TRUE);'和'VAR hasAtt = Attribute.IsDefined(类型的typeof (DisplayNameAttribute));' –

+0

我不这么认为,因为键入他的代码将返回'Int32',因此它会检查属性是否在'Int32'上定义。 @CodingYoshi上的 – CodingYoshi

+0

现货:) tnx – Ricky