C#字典转指定类型的技巧分享
作者:xyy123
这篇文章主要给大家介绍了C#字典转指定类型的技巧,文中通过代码示例介绍的非常详细,对大家的学习或工作有一定的帮助,有需要的朋友可以借鉴参考一下
创建Helper
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; } } }
使用演示
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,可以使用序列化巧妙转化
public static object DicToObj(Dictionary<string, object> dictionary) { string json = JsonConvert.SerializeObject(dictionary); return JsonConvert.DeserializeObject<object>(json); }
到此这篇关于C#字典转指定类型的技巧分享的文章就介绍到这了,更多相关C#字典转指定类型内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!