欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#字典轉(zhuǎn)指定類型的技巧分享

 更新時間:2023年10月17日 08:34:13   作者:xyy123  
這篇文章主要給大家介紹了C#字典轉(zhuǎn)指定類型的技巧,文中通過代碼示例介紹的非常詳細,對大家的學(xué)習(xí)或工作有一定的幫助,有需要的朋友可以借鑒參考一下

創(chuàng)建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>
        /// 字典類型轉(zhuǎn)化為對象
        /// </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; }
}

補充

但是上述方法無法將字典轉(zhuǎn)化為object,可以使用序列化巧妙轉(zhuǎn)化

 public static object DicToObj(Dictionary<string, object> dictionary)
    {
        string json = JsonConvert.SerializeObject(dictionary);
        return JsonConvert.DeserializeObject<object>(json);
    }

到此這篇關(guān)于C#字典轉(zhuǎn)指定類型的技巧分享的文章就介紹到這了,更多相關(guān)C#字典轉(zhuǎn)指定類型內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論