C#中获取类的属性和属性值

来源:互联网 发布:游戏公司美工 编辑:程序博客网 时间:2024/05/22 08:10

通过遍历来获取类的属性和属性的值,具体实现是通过反射获取属性再根据属性获取其值。具体代码如下。

/// <summary>        /// 获取对象的属性和值        /// </summary>        /// <param name="obj">对象</param>        /// <returns>返回属性与值一一对应的字典</returns>        public static Dictionary<string,string> GetPropertyValue<T>(T obj)        {            if (obj!=null)            {                Dictionary<string, string> propertyValue = new Dictionary<string, string>();                Type type = obj.GetType();                PropertyInfo[] propertyInfos = type.GetProperties();                foreach (PropertyInfo item in propertyInfos)                {                    propertyValue.Add(item.Name, (item.GetValue(obj,null)==null?"":item.GetValue(obj,null)).ToString());                }                return propertyValue;            }            return null;        }