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);
    }
相关推荐
苍何7 小时前
字节发力,豆包大模型2.0 震撼来袭(附 Trae 实测)
后端
苍何7 小时前
不会剪辑的人,开始用 AI 批量出爆款了
后端
苍何7 小时前
百度 APP 正式接入 OpenClaw,所有人限时免费!
后端
Volunteer Technology9 小时前
DynamicTP动态线程池(四)
java·spring boot·后端·spring
野犬寒鸦9 小时前
从零起步学习并发编程 || 第九章:Future 类详解及CompletableFuture 类在项目实战中的应用
java·开发语言·jvm·数据库·后端·学习
uzong9 小时前
软件工程师应该尽量改掉的坏习惯
后端
高山上有一只小老虎10 小时前
SpringBoot项目单元测试
spring boot·后端·单元测试
❀͜͡傀儡师11 小时前
Spring Boot Pf4j模块化能力设计思考
运维·spring boot·后端·pf4j
星空彼岸00713 小时前
SA-Token在SpringBoot中的实战指南
java·spring boot·后端
树獭叔叔13 小时前
大模型行为塑造:SFT 与 LoRA 深度解析
后端·aigc·openai