2012-01-20 18 views
5

私はループしたいクラスからプロパティのコレクションを持っています。 プロパティごとにカスタム属性があるので、それらをループしたいと思う。私は[正常に動作]プロパティをループにしようとすると属性が、そのようなプロパティからのカスタム属性#

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

のように定義されるよう

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

として、私は私の市クラスのカスタム属性を持っている。この特定のケースで と属性をループして、属性のforループを無視して何も返しません。私は

?Property.GetCustomAttributes(true)[0] 

を行うことができますカスタム属性を持つプロパティのイミディエイトウィンドウに行くとき

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); 
     } 
    } 
} 

それは私が仕事にこれに合うように見えることはできませんColumnMapName: "OtroID"

戻りますプログラム的には

+1

されるべきでは:慣例により、属性クラスは 'ColumnNameAttribute'と呼ばれるべきです。 – Heinzi

+3

'typeof(T)'の 'T'とは何ですか?イミディエイトウィンドウでは、Property.GetCustomAttribute(真)[0]が、foreachループ内で使用すると、代わりに –

+0

私はAttribute.GetCustomAttributesの過負荷を(表示されていないtypeparameterにGetCustomattributesを呼び出している)だけTypeパラメータを受け入れるを呼び出しています。属性を取得する行が正しいと確信していますか? – JMarsch

答えて

2

再投稿は、Tは、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)ではなくPropertiesを調べる必要があります。

はインテリセンスを使用して、Propertyオブジェクトのオフに呼び出すことができる方法を見てみましょう。

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); 
     } 
    } 
}