原
.net, c# ExpandoObject 构建动态类型。键值对Dictionary<string, object>转化成ExpandoObject

利用键值对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
}
}
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)
评价
排名
8
文章
222
粉丝
7
评论
7
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术