.net, c# ExpandoObject 构建动态类型。键值对Dictionary<string, object>转化成ExpandoObject 电脑版发表于:2024/5/13 10:37 利用键值对Dictionary动态构建ExpandoObject,ExpandoObject中包含了与字典相同的键值对作为属性 ``` using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; public static class DictionaryExtensions { public static ExpandoObject ToExpandoObject(this Dictionary<string, object> dictionary) { var expando = new ExpandoObject(); var expandoDict = (IDictionary<string, object>)expando; // Copy all the key-value pairs from the dictionary to the expando object foreach (var kvp in dictionary) { expandoDict[kvp.Key] = kvp.Value; } return expando; } } // 示例用法 class Program { static void Main() { var dict = new Dictionary<string, object> { { "Name", "John Doe" }, { "Age", 30 }, { "IsActive", true } }; dynamic expando = dict.ToExpandoObject(); Console.WriteLine(expando.Name); // 输出 "John Doe" Console.WriteLine(expando.Age); // 输出 30 Console.WriteLine(expando.IsActive); // 输出 True } } ```