从未知的类型字典获取密钥和值列表,而不使用动态 [英] get key and value list from unknown typed dictionary without using dynamic
问题描述
我正在尝试将一个字典转换为键值对,因此我可以对它进行一些特殊的解析并将其存储为字符串格式。我使用Unity,所以我不能使用动态关键字。这是我的设置
I am trying to convert a dictionary into key value pairs so I can do some special parsing on it and store it in string format. I am using Unity so I cannot use the dynamic keyword. Here is my setup
我有一些类,我正在遍历其属性并操纵它们的值并将它们放在一个新的字典中。问题是我不知道如何从一个字典获取键和值,我不知道这些类型,而不使用动态技巧。有什么想法吗?我将需要做同样的列表。
I have some class which I am iterating across its properties and manipulating their value and putting them in a new dictionary. The problem is I don't know how to get the keys and values out of a dictionary for which I do not know the types without using the dynamic trick. Any thoughts? I will need to do the same with lists.
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;
推荐答案
Dictionary< TKey,TValue& ;
还实现非通用的 IDictionary
界面,所以你可以使用它:
Dictionary<TKey, TValue>
also implements the non-generic IDictionary
interface, so you can use that:
IDictionary d = (IDictionary) o;
foreach(DictionaryEntry entry in d)
{
output[(string) entry.Key] = entry.Value;
}
请注意,如果键类型不是<$ c,这显然会失败$ c> string ...虽然您可以调用 ToString
而不是转换。
Note that this will obviously fail if the key type isn't string
... although you could call ToString
instead of casting.
您可以轻松地检查任何 IDictionary
实现,而不仅仅是 Dictionary<,>
- 甚至没有讨厌的反射检查:
You can easily check for any IDictionary
implementation, in fact - not just Dictionary<,>
- without even having the nasty reflection check:
IDictionary dictionary = info.GetValue(this, null) as IDictionary;
if (dictionary != null)
{
foreach (DictionaryEntry entry in dictionary)
{
output[(string) entry.Key] = entry.Value;
}
}
这篇关于从未知的类型字典获取密钥和值列表,而不使用动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!