创建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
{
///
/// 字典类型转化为对象
///
///
///
public T DicToObject(Dictionary 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()
{
{"name", "Tom"},
{"age", 25},
{"address", "Beijing"}
};
Helper helper = new Helper();
var person = helper.DicToObject(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 dictionary)
{
string json = JsonConvert.SerializeObject(dictionary);
return JsonConvert.DeserializeObject(json);
}