日期:2014-05-17  浏览次数:21692 次

怎么循环获取一个实体类每个字段的Display属性的值?
如图所示:


图中是我某个类的字段,我设置了某个字段的属性[Display(Name = "区域编码")],怎么获取该实体类下每个字段的Display属性?当然有些字段我没设置Display属性(比如ID)

------解决方案--------------------
参考代码:


   public static Dictionary<string, string> GetAuthors()
    {
        Dictionary<string, string> _dict = new Dictionary<string, string>();

        PropertyInfo[] props = typeof(Book).GetProperties();
        foreach (PropertyInfo prop in props)
        {
            object[] attrs = prop.GetCustomAttributes(true);
            foreach (object attr in attrs)
            {
                AuthorAttribute authAttr = attr as AuthorAttribute;
                if (authAttr != null)
                {
                    string propName = prop.Name;
                    string auth = authAttr.Name;

                    _dict.Add(propName, auth);
                }
            }
        }

        return _dict;
    }