【发布时间】:2012-02-15 10:31:10
【问题描述】:
所以我有一个我想循环遍历的类中的属性集合。 对于每个属性,我可能都有自定义属性,所以我想遍历这些属性。 在这种特殊情况下,我的 City Class 上有一个自定义属性
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"
我似乎无法让它以编程方式工作
【问题讨论】:
-
附带说明:按照惯例,属性类应称为
ColumnNameAttribute。 -
只是出于兴趣
typeof(T)中的T是什么?在即时窗口中,您正在调用 Property.GetCustomAttribute(true)[0] 但在 foreach 循环中,您在类型参数上调用 GetCustomattributes -
我没有看到只接受 Type 参数的 Attribute.GetCustomAttributes() 重载。你确定你检索属性的那一行是正确的吗?
-
@Dr.AndrewBurnett-Thompson 在这种特殊情况下,通用 T 是我的 City 类。我正在编写一个工具来将通用存储库映射到一端的类和另一端的数据库。好点,我以为我有那个,但我把它改成了 Object[] attrs = Property.GetCustomAttributes(true); foreach (var attr in attrs) 现在可以完美运行了:)
-
@Jordan 太棒了!很高兴它奏效了。而且该死,应该作为答案,但没关系;)
标签: c# asp.net reflection custom-attributes