【问题标题】:Convert dictionary to anonymous object将字典转换为匿名对象
【发布时间】:2011-12-29 11:12:53
【问题描述】:

我有一本字典

Dictionary<string, object> dict;

我通过键入从中获取值

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

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

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

我想知道是否有办法将其转换为对象,所以我可以输入如下内容:

string foo = dict.foo;

谢谢

【问题讨论】:

    标签: c# asp.net json


    【解决方案1】:

    如果您不知道字典的确切成员,您可以使用dynamic 来获得如下所示的漂亮语法。但是,如果您知道字典的成员和类型,then you could create your own class 并自己进行转换。可能存在一个自动执行此操作的框架。

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

    【讨论】:

    猜你喜欢
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-07-15
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    相关资源
    最近更新 更多