C#获取实体类属性名和值和DESCRIPTION值 | 遍历类对象

来源:互联网 发布:淘宝网汽车导航 编辑:程序博客网 时间:2024/04/28 23:26
//获取实体类里面所有的名称、值、DESCRIPTION值        public string getProperties<T>(T t)        {            string tStr = string.Empty;            if (t == null)            {                return tStr;            }            System.Reflection.PropertyInfo[] properties = t.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);            if (properties.Length <= 0)            {                return tStr;            }            foreach (System.Reflection.PropertyInfo item in properties)            {                string name = item.Name; //名称                object value = item.GetValue(t, null);  //值                string des = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute))).Description;// 属性值                if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))                {                    tStr += string.Format("{0}:{1}:{2},", name, value, des);                }                else                {                    getProperties(value);                }            }            return tStr;        }

原创粉丝点击