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);
    }
相关推荐
林太白2 小时前
❤Node09-用户信息token认证
数据库·后端·mysql·node.js
骆晨学长2 小时前
基于Springboot的助学金管理系统设计与实现
java·spring boot·后端
蒙娜丽宁3 小时前
深入理解Go语言中的接口定义与使用
开发语言·后端·golang·go
AskHarries3 小时前
java使用ByteBuffer进行多文件合并和拆分
java·后端
不染_是非3 小时前
Django学习实战篇六(适合略有基础的新手小白学习)(从0开发项目)
后端·python·学习·django
代码对我眨眼睛4 小时前
springboot从分层到解耦
spring boot·后端
The Straggling Crow4 小时前
go 战略
开发语言·后端·golang
ai安歌4 小时前
【JavaWeb】利用IDEA2024+tomcat10配置web6.0版本搭建JavaWeb开发项目
java·开发语言·后端·tomcat·web·intellij idea
尘浮生4 小时前
Java项目实战II基于Java+Spring Boot+MySQL的作业管理系统设计与实现(源码+数据库+文档)
java·开发语言·数据库·spring boot·后端·mysql·spring
程序员阿鹏5 小时前
ArrayList 与 LinkedList 的区别?
java·开发语言·后端·eclipse·intellij-idea