从未知类型的字典中获取键和值列表,而不使用动态
本文关键字:动态 列表 键和值 类型 未知 字典 获取 | 更新日期: 2023-09-27 18:10:31
我正在尝试将字典转换为键值对,以便我可以对其进行一些特殊解析并将其存储为字符串格式。我正在使用Unity,所以我不能使用动态关键字。这是我的设置
我有一些类,我正在迭代它的属性并操作它们的值,并将它们放入新字典中。问题是,如果不使用动态技巧,我不知道如何从字典中获取键和值,因为我不知道类型。任何想法吗?我将需要对列表做同样的事情。
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
接口,因此您可以使用它:
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;
}
}