C# 字典转指定类型

创建Helper

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace dicToObj
{
    internal class Helper
    {
        /// <summary>
        /// 字典类型转化为对象
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public T DicToObject<T>(Dictionary<string, object> dic) where T : new()
        {
            var md = new T();
            CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
            TextInfo textInfo = cultureInfo.TextInfo;
            foreach (var d in dic)
            {
                var filed = textInfo.ToTitleCase(d.Key);
                try
                {
                    var value = d.Value;
                    md.GetType().GetProperty(filed).SetValue(md, value);
                }
                catch (Exception e)
                {

                }
            }
            return md;
        }
    }
}

使用演示

csharp 复制代码
using dicToObj;

var dic = new Dictionary<string, object>()
{
    {"name", "Tom"},
    {"age", 25},
    {"address", "Beijing"}
};

Helper helper = new Helper();
var person = helper.DicToObject<Person>(dic);


Console.WriteLine(person);
Console.WriteLine();

public record Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}

补充

但是上述方法无法将字典转化为object,可以使用序列化巧妙转化

csharp 复制代码
 public static object DicToObj(Dictionary<string, object> dictionary)
    {
        string json = JsonConvert.SerializeObject(dictionary);
        return JsonConvert.DeserializeObject<object>(json);
    }
相关推荐
RemainderTime4 分钟前
基于 Spring AI + DeepSeek:构建AI Agent 企业级服务与底层原理解析
人工智能·后端·spring·ai
希望永不加班8 分钟前
SpringBoot Web 模块核心组件:从 DispatcherServlet 讲起
java·前端·spring boot·后端·spring
流星雨在线16 分钟前
SpringBoot 从开发到打包发布完整教程(对比 Node.js)
spring boot·后端·node.js
希望永不加班25 分钟前
SpringBoot 接口测试:Postman 与 JUnit 5 实战
java·spring boot·后端·junit·postman
tumeng071129 分钟前
跟据spring boot版本,查看对应的tomcat,并查看可支持的tomcat的版本范围
spring boot·后端·tomcat
深邃-29 分钟前
字符函数和字符串函数(2)
c语言·数据结构·c++·后端·算法·restful
小码哥_常9 小时前
Spring Boot 牵手Spring AI,玩转DeepSeek大模型
后端
0xDevNull9 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
华洛9 小时前
我用AI做了一个48秒的真人精品漫剧,不难也不贵
前端·javascript·后端
WZTTMoon9 小时前
Spring Boot 中Servlet、Filter、Listener 四种注册方式全解析
spring boot·后端·servlet