C#對象轉換成字典

#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(); // 獲取對象對應的類, 對應的類型string

PropertyInfo[] pi = t.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 獲取當前type公共屬性io

foreach (PropertyInfo p in pi)
{
MethodInfo m = p.GetGetMethod();object

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;
}
#endregionforeach

相關文章
相關標籤/搜索