C#中字典Dictionary与自定义类型CustomType之间的转换
思路:
可以使用反射System.Reflection来获取类的具体属性,
属性名称就映射字典的键Key。
新建控制台程序DictionaryCustomClassConversionDemo
第一步、新建关键转换类ConversionUtil。
类ConversionUtil的源代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;namespace DictionaryCustomClassConversionDemo
{/// <summary>/// 字典Dictionary与自定义类CustomClass属性之间的转化/// 斯内科 2024-05-10/// </summary>public class ConversionUtil{/// <summary>/// 将一个实体类的属性转化为键值对集合,键为属性名PropertyName,值为对应的值/// </summary>/// <typeparam name="T">一种自定义类,该类必须已实例化</typeparam>/// <param name="obj">实例化后的类对象</param>/// <returns>返回转化后的字典</returns>public static Dictionary<string, object> CustomClassToDictionary<T>(T obj) where T : class, new(){Dictionary<string, object> dict = new Dictionary<string, object>();Type type = typeof(T);PropertyInfo[] propertyInfos = type.GetProperties();for (int i = 0; i < propertyInfos.Length; i++){string key = propertyInfos[i].Name;object val = propertyInfos[i].GetValue(obj);dict.Add(key, val);}return dict;}/// <summary>/// 将字典转化为实例化类,如果类的属性名称在字典中存在该键key,就使用该键对应的值为类的属性key赋值【注意,转化可能因值的类型、范围等不同而导致失败】/// 如果类的属性名称在字典中不存在该键key,则不进行赋值,只是按属性对应类型的默认值处理/// </summary>/// <typeparam name="T">要转化的目标类型</typeparam>/// <param name="dict">键值对字典</param>/// <returns>要获取的目标实例化类对象,如果字典为空,则按类的默认值处理</returns>public static T DictionaryToCustomClass<T>(Dictionary<string, object> dict) where T : class{T obj = default(T);if (dict == null || dict.Count == 0) {return obj;}Type type = typeof(T);obj = (T)Activator.CreateInstance(type);PropertyInfo[] propertyInfos = type.GetProperties();for (int i = 0; i < propertyInfos.Length; i++){string key = propertyInfos[i].Name;if (dict.ContainsKey(key)) {propertyInfos[i].SetValue(obj, dict[key]);}}return obj;}}
}
二、新建实体测试类TestClass。
测试类TestClass源程序如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DictionaryCustomClassConversionDemo
{/// <summary>/// 测试类/// </summary>public class TestClass{/// <summary>/// 主键/// </summary>public int CoreID { get; set; }/// <summary>/// 档位编号/// </summary>public int LevelId { get; set; }/// <summary>/// 电压下限/// </summary>public double VoltageMin { get; set; }/// <summary>/// 电压上限/// </summary>public double VoltageMax { get; set; }/// <summary>/// 内阻值/// </summary>public string Resistance { get; set; }/// <summary>/// 修改时间/// </summary>public DateTime ModifyTime { get; set; }public override string ToString(){return $"{{CoreID:{CoreID},\nLevelId:{LevelId},\nVoltageMin:{VoltageMin},\nVoltageMax:{VoltageMax},\nResistance:{Resistance},\nModifyTime:{ModifyTime.ToString("yyyy-MM-dd HH:mm:ss")}}}";}}
}
三、调用测试Program如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace DictionaryCustomClassConversionDemo
{class Program{static void Main(string[] args){Console.SetWindowSize(100, 60);try{TestClass testClass = new TestClass(){CoreID = 6,LevelId = 3,VoltageMin = 3.10,VoltageMax = 3.99,Resistance = "888MΩ",ModifyTime = DateTime.Now};Console.WriteLine($"--------打印原对象信息:--------");Console.WriteLine(testClass);Dictionary<string, object> dict = ConversionUtil.CustomClassToDictionary(testClass);Console.WriteLine("--------打印类对象转化后的字典信息:--------");for (int i = 0; i < dict.Count; i++){KeyValuePair<string, object> keyValuePair = dict.ElementAt(i);Console.WriteLine($"{keyValuePair.Key}:{keyValuePair.Value}");}Console.WriteLine();Console.WriteLine("--------测试字典转化为类--------");dict["Resistance"] = "333MΩ";dict["LevelId"] = 1;dict["VoltageMax"] = 5;dict.Add("额外参数", "额外值");Console.WriteLine("--------打印原字典信息1:--------");for (int i = 0; i < dict.Count; i++){KeyValuePair<string, object> keyValuePair = dict.ElementAt(i);Console.WriteLine($"{keyValuePair.Key}:{keyValuePair.Value}");}TestClass testObj1 = ConversionUtil.DictionaryToCustomClass<TestClass>(dict);Console.WriteLine("--------打印字典转化为类对象1--------");Console.WriteLine(testObj1);Console.WriteLine();dict["Resistance"] = 66666;dict["LevelId"] = 5;Console.WriteLine("--------打印原字典信息2:--------");for (int i = 0; i < dict.Count; i++){KeyValuePair<string, object> keyValuePair = dict.ElementAt(i);Console.WriteLine($"{keyValuePair.Key}:{keyValuePair.Value}");}TestClass testObj2 = ConversionUtil.DictionaryToCustomClass<TestClass>(dict);Console.WriteLine("--------打印字典转化为类对象2--------");Console.WriteLine(testObj2);}catch (Exception ex) {Console.WriteLine($"{ex.Message}.异常类型【{ex.GetType()}】");}Console.ReadLine();}}
}