C#强制转换Dictionary< string,AnyType>到字典<字符串,对象> (涉及反思) [英] C# cast Dictionary<string, AnyType> to Dictionary<string, Object> (Involving Reflection)
问题描述
是否可以将 Dictionary< string,Anything>
转换为一致的中间泛型类型?这样我就可以转换< string,string>
,< string,bool>
,< string,int>
,< string,任何>
都属于相同类型的字典吗?
Is it possible to cast a Dictionary<string, Anything>
to a consistent intermediate generic type? So I would be able to cast <string, string>
, <string, bool>
, <string, int>
, <string, anything>
all to the same type of dictionary?
我正在研究一个使用大量反射的项目,我需要能够处理以下字典类型:
I am working on a project that is using heavy reflection and I need to be able to process DIctionary types as such:
FieldInfo field = this.GetType().GetField(fieldName);
Dictionary<string, Object> dict = (Dictionary<string, Object>)field.GetValue(this);
上面的代码是我目前拥有的,程序在从field.GetValue强制转换时总是失败通用 Dictionary< string,Object>
。
The above code is what I currently have and the program always fails at the cast from field.GetValue to the generic Dictionary<string, Object>
.
有没有办法做到这一点?还是我应该找出其他方法来处理这些词典?
Is there a way to do this? Or should I just figure out a different way to process these Dictionaries?
任何帮助将不胜感激。
推荐答案
在 AakashM的答案之后,Cast似乎没有发挥作用。您可以通过使用一些辅助方法来解决它:
Following AakashM's answer, the Cast doesn't seem to play ball. You can get around it by using a little helper method though:
IDictionary dictionary = (IDictionary)field.GetValue(this);
Dictionary<string, object> newDictionary = CastDict(dictionary)
.ToDictionary(entry => (string)entry.Key,
entry => entry.Value);
private IEnumerable<DictionaryEntry> CastDict(IDictionary dictionary)
{
foreach (DictionaryEntry entry in dictionary)
{
yield return entry;
}
}
在这种情况下,键入foreach的鸭子很方便。
The duck typing in foreach is handy in this instance.
这篇关于C#强制转换Dictionary< string,AnyType>到字典<字符串,对象> (涉及反思)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!