如何将C#嵌套对象转换为冒号分隔键的IConfiguration适配字典
对象转.NET分层配置字典解决方案
.NET 生态没有单独公开的静态转换方法,但可以通过两种方式快速实现需求,无需手动拼接键名:
方案1:通用扩展方法(推荐)
直接写一个递归扩展方法,支持任意嵌套类,和.NET配置的冒号分隔规则完全对齐,可直接用于内存配置源:
using System.Collections.Generic; using System.Reflection; public static class ObjectToConfigurationExtensions { /// <summary> /// 将任意对象转换为符合.NET配置规则的冒号分隔键值对字典 /// </summary> /// <param name="obj">要转换的对象</param> /// <param name="rootKey">根键名,不传则以类名作为根键</param> public static Dictionary<string, string> ToConfigurationDictionary(this object obj, string rootKey = null) { var result = new Dictionary<string, string>(); rootKey ??= obj.GetType().Name; FlattenObject(obj, rootKey, result); return result; } private static void FlattenObject(object obj, string prefix, Dictionary<string, string> result) { if (obj == null) return; var type = obj.GetType(); // 处理值类型、字符串等基础类型 if (type.IsPrimitive || type == typeof(string) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(Guid)) { result[prefix] = obj.ToString(); return; } // 处理复杂类型,遍历公共属性递归展开 foreach (var prop in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { var propValue = prop.GetValue(obj); var currentKey = $"{prefix}:{prop.Name}"; FlattenObject(propValue, currentKey, result); } } }
使用示例
针对你给出的Person类,直接调用即可得到目标字典:
// 实例化你的对象 var person = new Person { Name = "Jack", Contact = new Contact { Email = "jack@gmail.com", Phone = "13xxxxxxxxx" } }; // 转换为配置字典 Dictionary<string, string> settings = person.ToConfigurationDictionary();
转换后输出的字典结构和你要求的完全一致:
Person:Name→JackPerson:Contact:Email→jack@gmail.comPerson:Contact:Phone→13xxxxxxxxx
生成的字典可以直接传入AddInMemoryCollection方法加载为配置源,后续通过IConfigurationRoot正常读取或者绑定回对象。
方案2:适配数组/集合的扩展说明
如果需要支持集合/数组类型的转换,只需要在FlattenObject方法中添加对IEnumerable类型的判断,按索引拼接键名即可,示例逻辑:
// 加在基础类型判断之后,复杂类型遍历之前 if (obj is IEnumerable enumerable && obj is not string) { var index = 0; foreach (var item in enumerable) { FlattenObject(item, $"{prefix}:{index}", result); index++; } return; }
生成的数组键符合.NET配置规则,格式为Person:Hobbies:0、Person:Hobbies:1。
内容的提问来源于stack exchange,提问作者Haha
相关产品推荐
相关产品推荐

