属性,所以我有属性的,从我的类的集合,我想通过循环。 对于每个属性,我可能有自定义属性,所以我想循环这些。 在这种特殊情况下,我有我的城市类的自定义属性,因为这样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"
我似乎无法适应这种工作编程虽然
作为一个边注:按照惯例,属性类应该被称为'ColumnNameAttribute'。 – Heinzi
出于兴趣,'typeof(T)'中的T是什么?在即时窗口中,您调用Property.GetCustomAttribute(true)[0],但在foreach循环内您调用类型参数上的GetCustomattributes而不是 –
我没有看到仅接受Type参数的Attribute.GetCustomAttributes()的重载。你确定你检索属性的行是正确的吗? – JMarsch