2012-01-20 148 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); 
     } 
    } 
}