C#自定义属性从属性

编程入门 行业动态 更新时间:2024-10-15 14:18:31
本文介绍了C#自定义属性从属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

所以我有属性的,从我的类的集合,我想通过循环。对于每个属性我可能有自定义属性,所以我想通过这些循环。在这种特殊情况下我有我的城市类的自定义属性这样

so I have a collection of Properties from my class which I want to loop through. For each property I may have custom attributes so I want to loop through those. In this particular case I have a custom attribute on my City Class as such

public class City { [ColumnName("OtroID")] public int CityID { get; set; } [Required(ErrorMessage = "Please Specify a City Name")] public string CityName { get; set; } }

的属性被定义为这样的

The attribute is defined as such

[AttributeUsage(AttributeTargets.All)] public class ColumnName : System.Attribute { public readonly string ColumnMapName; public ColumnName(string _ColumnName) { this.ColumnMapName= _ColumnName; } }

当我通过属性通过属性[工作正常],然后循环尝试循环,它只是忽略了for循环的属性,并且没有返回。

WHen I try to loop through the properties [which works fine] and then loop through the attributes it just ignores the for loop for the attribute and returns nothing.

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); } }

当我去眼前的窗口,有一个自定义属性,我可以做财产

When I go to the immediate window for the property that has a custom attribute I can do

?Property.GetCustomAttributes(true)[0]

这将返回 Col​​umnMapName:OtroID

我似乎无法适应这虽然

推荐答案

的由原来的问题的意见重新发布,在作者要求的

只是出于兴趣是什么的typeof(T)笔?

Just out of interest what is T in typeof(T)?

在您呼叫Property.GetCustomAttribute(真)[0],但foreach循环里面你在一个typeparameter调用GetCustomattributes而不是立即窗口。

In the immediate window you are calling Property.GetCustomAttribute(true)[0] but inside the foreach loop you are calling GetCustomattributes on a typeparameter instead.

这行:

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

应然是这个

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

最好的问候,

更多推荐

C#自定义属性从属性

本文发布于:2023-11-17 00:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608090.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:从属性   自定义   属性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!