C# Model(模型) 转 Hashtable
灵感来源:https://blog.csdn.net/anonymous_qsh/article/details/78596695
public static Hashtable ObjectToMap(object obj, bool isIgnoreNull = false) { Hashtable map = new Hashtable(); 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 || !isIgnoreNull) { map.Add(p.Name, m.Invoke(obj, new object[] { })); // 向字典添加元素 } } } return map; }
https://blog.csdn.net/anonymous_qsh/article/details/78596695
/// <summary> /// 对象转换为字典 /// </summary> /// <param name="obj">待转化的对象</param> /// <param name="isIgnoreNull">是否忽略NULL 这里我不需要转化NULL的值,正常使用可以不穿参数 默认全转换</param> /// <returns></returns> public static Dictionary<string, object> ObjectToMap(object obj, bool isIgnoreNull = false) { Dictionary<string, object> map = new Dictionary<string, object>(); 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 || !isIgnoreNull) { map.Add(p.Name, m.Invoke(obj, new object[] { })); // 向字典添加元素 } } } return map; }
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构