C#来自属性的自定义属性
所以我有一个类中的属性集合,我想循环使用它。 对于每个属性,我可能都有自定义属性,所以我想循环这些属性。 在这种特殊情况下,我的City类上有一个自定义属性C#来自属性的自定义属性,c#,asp.net,reflection,custom-attributes,C#,Asp.net,Reflection,Custom Attributes,所以我有一个类中的属性集合,我想循环使用它。 对于每个属性,我可能都有自定义属性,所以我想循环这些属性。 在这种特殊情况下,我的City类上有一个自定义属性 public class City { [ColumnName("OtroID")] public int CityID { get; set; } [Required(ErrorMessage = "Please Specify a City Name")] public string CityNam
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”
我似乎无法通过编程实现这一点,尽管我相信您希望这样做:
PropertyInfo[] propCollection = type.GetProperties();
foreach (PropertyInfo property in propCollection)
{
foreach (var attribute in property.GetCustomAttributes(true))
{
if (attribute is ColumnName)
{
}
}
}
在内部外观中,您应该研究属性,而不是(T)的类型 使用intellisense并查看可以调用属性对象的方法 GetCustomAttributes(布尔)可能对您很重要。
这将返回一个数组,您可以在其上使用LINQ快速返回符合您要求的所有属性。我得到的这段代码的值为
x
为“OtroID Maps to CityID”
应作者要求,从原始问题的评论中转载
只是出于兴趣,T的类型是什么
在即时窗口中,您正在调用Property.GetCustomAttribute(true)[0],但在foreach循环中,您正在对typeparameter调用GetCustomattributes
这一行:
System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(T));
应该是这个
System.Attribute[] attrs = property.GetCustomAttributes(true);
最好的问候,作为旁注:按照惯例,属性类应该被称为
columnnamattribute
。只是出于兴趣,typeof(T)
中的T
是什么?在即时窗口中,您正在调用Property.GetCustomAttribute(true)[0],但在foreach循环中,您正在对一个typeparameter instedi调用GetCustomattributes,但没有看到仅接受一个类型参数的Attribute.GetCustomattributes()重载。您确定检索属性的行是正确的吗?@Dr.AndrewBurnett-Thompson在这种特殊情况下,泛型T是我的城市类。我正在编写一个工具,将通用存储库映射到一端的类和另一端的数据库。很好的一点,我认为我已经在那里了,但我把它改为Object[]attrs=Property.GetCustomAttributes(true);foreach(attrs中的var attr)现在可以完美工作:)@Jordan great!很高兴它起作用了。还有,当,应该把它作为答案,但不管怎样;)
System.Attribute[] attrs = property.GetCustomAttributes(true);