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

use*_*539 2 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;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

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

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

请注意,如果密钥类型不是,这显然会失败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;
    }
}
Run Code Online (Sandbox Code Playgroud)