【问题标题】:get key and value list from unknown typed dictionary without using dynamic从未知类型的字典中获取键和值列表而不使用动态
【发布时间】:2014-08-17 21:46:28
【问题描述】:

我正在尝试将字典转换为键值对,以便对其进行特殊解析并将其存储为字符串格式。我正在使用 Unity,所以我不能使用 dynamic 关键字。这是我的设置

我有一些类,我正在遍历它的属性并操纵它们的值并将它们放入一个新字典中。问题是我不知道如何在不使用动态技巧的情况下从我不知道类型的字典中获取键和值。有什么想法吗?我需要对列表做同样的事情。

    Type t = GetType();
    Dictionary<string, object> output = new Dictionary<string, object>();
    foreach(PropertyInfo info in t.GetProperties())
    {
        object o = info.GetValue(this, null);
        if(info.PropertyType.GetGenericTypeDefinition() == typeof(Dictionary<,>))
        {
            Dictionary<string, object> d = new Dictionary<string, object>();
            foreach(object key in o) //not valid
            {
                object val = DoSomething(o[key]);//not valid
                output[key] = val;
            }
        }
        else if(info.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
        {

        }
    }
    return output;

【问题讨论】:

    标签: c# dictionary


    【解决方案1】:

    Dictionary&lt;TKey, TValue&gt; 还实现了非泛型 IDictionary 接口,因此您可以使用它:

    IDictionary d = (IDictionary) o;
    foreach(DictionaryEntry entry in d)
    {
        output[(string) entry.Key] = entry.Value;
    }
    

    请注意,如果密钥类型不是 string,这显然会失败...尽管您可以调用 ToString 而不是强制转换。

    实际上,您可以轻松检查 任何 IDictionary 实现 - 不仅仅是 Dictionary&lt;,&gt; - 甚至不需要进行讨厌的反射检查:

    IDictionary dictionary = info.GetValue(this, null) as IDictionary;
    if (dictionary != null)
    {
        foreach (DictionaryEntry entry in dictionary)
        {
            output[(string) entry.Key] = entry.Value;
        }
    }
    

    【讨论】:

    • 感谢您的快速答复!让我试试这个,看看它是否有效。有些事情在其他人做的IOS上不能很好地工作。我会回来报告的。可能要等到星期一
    • 我觉得应该是 output[(string) entry.Key] = d[entry.Key];
    • @user2292539:不完全是——应该是output[(string) entry.Key] = entry.Value;——当我们已经获得了带有值的条目时,就不需要按键查找了。我已经确定了答案。
    • 所以在想了一会儿之后,我不知道为什么我不首先使用序列化来处理我想要的东西,但这仍然是一个值得学习的好东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2022-06-21
    相关资源
    最近更新 更多