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);
    }
相关推荐
一点程序3 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
怪兽源码5 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
csdn_aspnet5 小时前
ASP.NET Core 中的依赖注入
后端·asp.net·di·.net core
昊坤说不出的梦6 小时前
【实战】监控上下文切换及其优化方案
java·后端
疯狂踩坑人6 小时前
【Python版 2026 从零学Langchain 1.x】(二)结构化输出和工具调用
后端·python·langchain
橘子师兄8 小时前
C++AI大模型接入SDK—ChatSDK封装
开发语言·c++·人工智能·后端
@ chen8 小时前
Spring事务 核心知识
java·后端·spring
一点技术9 小时前
基于SpringBoot的选课调查系统
java·spring boot·后端·选课调查系统
RANCE_atttackkk10 小时前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程
好好研究11 小时前
Spring Boot - Thymeleaf模板引擎
java·spring boot·后端·thymeleaf