来自属性的C#自定义属性

所以我有一个我想要循环的类的属性集合。 对于每个属性,我可能有自定义属性,所以我想循环这些属性。 在这种特殊情况下,我在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"

我似乎无法以编程方式工作

根据作者的要求,重新发布原始问题的评论

只是出于兴趣,什么是T in typeof(T)?

在即时窗口中,您调用Property.GetCustomAttribute(true)[0],但在foreach循环中,您在类型参数上调用GetCustomattributes。

这一行:

 System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(T)); 

应该是这样的

 System.Attribute[] attrs = property.GetCustomAttributes(true); 

最好的祝福,

你想这样做我相信:

 PropertyInfo[] propCollection = type.GetProperties(); foreach (PropertyInfo property in propCollection) { foreach (var attribute in property.GetCustomAttributes(true)) { if (attribute is ColumnName) { } } } 

我得到这个代码最终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); } } } 

在内部外观中,您应该研究属性,而不是类型(T)。

使用intellisense并查看可以调用Property对象的方法。

Property.GetCustomAttributes(Boolean)可能对您很重要。 这将返回一个数组,您可以在其上使用LINQ快速返回符合您要求的所有属性。