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);
    }
相关推荐
aramae7 分钟前
模拟实现strcmp()(C语言)
c语言·开发语言·后端
根目录下的猫2 小时前
RK3588适配的轻量级AI模型推荐
人工智能·后端·python·目标检测
星栈3 小时前
用 Rust 写 Agent 服务 -- adk-rust 上手记
后端·agent
杨运交3 小时前
[071][验证码模块]基于Spring拦截器的验证码认证设计思想
java·后端·spring
LucianaiB4 小时前
我用豆包工作 Seed-2.1-pro,复刻了 QQ 时代爆红的魔术图片
后端
码事漫谈4 小时前
智谱 ZCode 静默上传 Git 历史:48 小时信任危机复盘
后端
掘金码甲哥5 小时前
当对话模型遇上向量模型,vllm production stack 又该如何应对?
后端
传奇开心果编程5 小时前
【springboot基础语法学与练】第 1 课:从零开始
java·spring boot·后端·学习
IT_陈寒5 小时前
Java线程池用错参数,我的服务居然悄悄崩溃了
前端·人工智能·后端