2012-01-20 149 views
5

属性,所以我有属性的,从我的类的集合,我想通过循环。 对于每个属性,我可能有自定义属性,所以我想循环这些。 在这种特殊情况下,我有我的城市类的自定义属性,因为这样C#自定义属性从

public class City 
{ 
    [ColumnName("OtroID")] 
    public int CityID { get; set; } 
    [Required(ErrorMessage = "Please Specify a City Name")] 
    public string CityName { get; set; } 
} 

的属性定义为这样

[AttributeUsage(AttributeTargets.All)] 
public class ColumnName : System.Attribute 
{ 
    public readonly string ColumnMapName; 
    public ColumnName(string _ColumnName) 
    { 
     this.ColumnMapName= _ColumnName; 
    } 
} 

当我尝试遍历性[工作正常]和然后遍历它只忽略for循环的属性,并不返回任何内容。

foreach (PropertyInfo Property in PropCollection) 
//Loop through the collection of properties 
//This is important as this is how we match columns and Properties 
{ 
    System.Attribute[] attrs = 
     System.Attribute.GetCustomAttributes(typeof(T)); 
    foreach (System.Attribute attr in attrs) 
    { 
     if (attr is ColumnName) 
     { 
      ColumnName a = (ColumnName)attr; 
      var x = string.Format("{1} Maps to {0}", 
       Property.Name, a.ColumnMapName); 
     } 
    } 
} 

当我去到即时窗口,有一个自定义属性,我可以做

?Property.GetCustomAttributes(true)[0] 

属性将返回ColumnMapName: "OtroID"

我似乎无法适应这种工作编程虽然

+1

作为一个边注:按照惯例,属性类应该被称为'ColumnNameAttribute'。 – Heinzi

+3

出于兴趣,'typeof(T)'中的T是什么?在即时窗口中,您调用Property.GetCustomAttribute(true)[0],但在foreach循环内您调用类型参数上的GetCustomattributes而不是 –

+0

我没有看到仅接受Type参数的Attribute.GetCustomAttributes()的重载。你确定你检索属性的行是正确的吗? – JMarsch

回答

2

从原来的问题的评论转播,在作者要求

只是出于兴趣是什么T IN的typeof(T)?

在即时窗口中,您调用Property.GetCustomAttribute(true)[0],但在foreach循环内您改为在类型参数上调用GetCustomattributes。

这条线:

System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(T)); 

应该是这个

System.Attribute[] attrs = property.GetCustomAttributes(true); 

最好的问候,

8

你想这样做,我相信:

PropertyInfo[] propCollection = type.GetProperties(); 
foreach (PropertyInfo property in propCollection) 
{ 
    foreach (var attribute in property.GetCustomAttributes(true)) 
    { 
     if (attribute is ColumnName) 
     { 
     } 
    } 
} 
1

在内部看,你应该调查的属性,而不是将typeof(T)。

使用智能感知和看一看,你可以取消该物业对象的方法。

Property.GetCustomAttributes(布尔)可能是重要的给你。 这将返回一个数组,你可以使用LINQ它来快速返回所有符合您要求的属性。

1

我得到这个代码x"OtroID Maps to CityID"的价值就结了。

var props = typeof(City).GetProperties(); 
foreach (var prop in props) 
{ 
    var attributes = Attribute.GetCustomAttributes(prop); 
    foreach (var attribute in attributes) 
    { 
     if (attribute is ColumnName) 
     { 
      ColumnName a = (ColumnName)attribute; 
      var x = string.Format("{1} Maps to {0}",prop.Name,a.ColumnMapName); 
     } 
    } 
}