从未知类型字典中获取键和值列表,而不使用动态

时间:2014-06-26 21:39:03

标签: c# dictionary

我正在尝试将字典转换为键值对,因此我可以对其进行一些特殊的解析并将其存储为字符串格式。我正在使用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;

1 个答案:

答案 0 :(得分:6)

Dictionary<TKey, TValue>还实现了非通用IDictionary接口,因此您可以使用它:

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

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

您可以轻松检查任何 IDictionary实施,事实上 - 不只是Dictionary<,> - 甚至没有讨厌的反思检查:

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