C# 将字典转换为匿名对象
我有一本字典C# 将字典转换为匿名对象,c#,asp.net,json,C#,Asp.net,Json,我有一本字典 Dictionary<string, object> dict; 字典是一个序列化的JSON结果 serializer.Deserialize<Dictionary<string, object>>(HttpContext.Current.Request["JSON"]); 谢谢如果您不知道字典的确切成员,您可以使用动态获得如下所示的漂亮语法。但是,如果您知道字典的成员和类型,并且自己进行转换。可能存在一个自动执行此操作的框架 using S
Dictionary<string, object> dict;
字典是一个序列化的JSON结果
serializer.Deserialize<Dictionary<string, object>>(HttpContext.Current.Request["JSON"]);
谢谢如果您不知道字典的确切成员,您可以使用
动态
获得如下所示的漂亮语法。但是,如果您知道字典的成员和类型,并且自己进行转换。可能存在一个自动执行此操作的框架
using System;
using System.Collections.Generic;
using System.Text;
using System.Dynamic;
namespace DynamicTest
{
public class DynamicDictionary : DynamicObject
{
Dictionary<string, object> dict;
public DynamicDictionary(Dictionary<string, object> dict)
{
this.dict = dict;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dict[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return dict.TryGetValue(binder.Name, out result);
}
}
class Program
{
static void Main(string[] args)
{
dynamic foo = new DynamicDictionary(new Dictionary<string, object> { { "test1", 1 } });
foo.test2 = 2;
Console.WriteLine(foo.test1); // Prints 1
Console.WriteLine(foo.test2); // Prints 2
}
}
}
使用系统;
使用System.Collections.Generic;
使用系统文本;
运用系统动力学;
命名空间动态测试
{
公共类DynamicDictionary:DynamicObject
{
词典词典;
公共动态词典(字典目录)
{
this.dict=dict;
}
public override bool TrySetMember(SetMemberBinder绑定器,对象值)
{
dict[binder.Name]=值;
返回true;
}
公共重写bool TryGetMember(GetMemberBinder绑定器,输出对象结果)
{
返回dict.TryGetValue(binder.Name,out结果);
}
}
班级计划
{
静态void Main(字符串[]参数)
{
dynamicfoo=新的DynamicDictionary(新字典{{“test1”,1});
foo.test2=2;
Console.WriteLine(foo.test1);//打印1
Console.WriteLine(foo.test2);//打印2
}
}
}
该框架确实存在,并且被称为
string foo = dict.foo;
using System;
using System.Collections.Generic;
using System.Text;
using System.Dynamic;
namespace DynamicTest
{
public class DynamicDictionary : DynamicObject
{
Dictionary<string, object> dict;
public DynamicDictionary(Dictionary<string, object> dict)
{
this.dict = dict;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
dict[binder.Name] = value;
return true;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return dict.TryGetValue(binder.Name, out result);
}
}
class Program
{
static void Main(string[] args)
{
dynamic foo = new DynamicDictionary(new Dictionary<string, object> { { "test1", 1 } });
foo.test2 = 2;
Console.WriteLine(foo.test1); // Prints 1
Console.WriteLine(foo.test2); // Prints 2
}
}
}