C#自定义属性从属性 [英] C# Custom Attributes from Properties

查看:147
本文介绍了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#自定义属性从属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆