私はループしたいクラスからプロパティのコレクションを持っています。 プロパティごとにカスタム属性があるので、それらをループしたいと思う。私は[正常に動作]プロパティをループにしようとすると属性が、そのようなプロパティからのカスタム属性#
[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"
戻りますプログラム的には
されるべきでは:慣例により、属性クラスは 'ColumnNameAttribute'と呼ばれるべきです。 – Heinzi
'typeof(T)'の 'T'とは何ですか?イミディエイトウィンドウでは、Property.GetCustomAttribute(真)[0]が、foreachループ内で使用すると、代わりに –
私はAttribute.GetCustomAttributesの過負荷を(表示されていないtypeparameterにGetCustomattributesを呼び出している)だけTypeパラメータを受け入れるを呼び出しています。属性を取得する行が正しいと確信していますか? – JMarsch