转换字典匿名对象 [英] Convert dictionary to anonymous object

查看:164
本文介绍了转换字典匿名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典

Dictionary<string, object> dict;

和我通过键入从它那里得到的值

And i get values from it by typing

string foo = dict["foo"].ToString();

这本字典是一个序列化的JSON结果。

The dictionary is a serialized JSON result.

serializer.Deserialize<Dictionary<string, object>>(HttpContext.Current.Request["JSON"]);

我想知道,如果thers的方式将其转换为一个对象,所以我可以输入类似:

What i would like to know if thers a way to convert it to an object, so i can type something like:

string foo = dict.foo;

感谢

推荐答案

如果你不知道你可以使用字典的确切成员动态来获得$下面p $ ptty语法如图所示。但是,如果你知道字典的成员和类型,<一个href=\"http://stackoverflow.com/questions/2246694/how-to-convert-json-object-to-custom-c-sharp-object\">then你可以创建自己的类并自己​​进行转换。则可能存在的框架来自动做到这一点。

If you don't know the exact members of the dictionary you can use dynamic to get a pretty syntax as shown below. However, if you know the members of the dictionary and the types, then you could create your own class and do the conversion yourself. There might exists a framework to do that automatically.

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
        }
    }
}

这篇关于转换字典匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆