1. 程式人生 > 其它 >物件轉成字典

物件轉成字典

    public static class ObjectToMapServie
    {
        #region 物件轉成字典
        /// <summary>
        /// 物件轉換為字典
        /// </summary>
        /// <param name="obj">待轉化的物件</param>
        /// <returns></returns>
        public static Dictionary<string, string> ObjectToMap(object
obj) { Dictionary<string, string> map = new Dictionary<string, string>(); Type t = obj.GetType(); // 獲取物件對應的類, 對應的型別 PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 獲取當前type公共屬性 foreach (PropertyInfo p in
pi) { MethodInfo m = p.GetGetMethod(); if (m != null && m.IsPublic) { // 進行判NULL處理 if (m.Invoke(obj, new object[] { }) != null) { map.Add(p.Name, m.Invoke(obj,
new object[] { }).ToString()); // 向字典新增元素 } } } return map; } #endregion }