如果“值”是一个传入的通用字典,其类型未知/无关紧要,我如何获取它的条目并将它们放入类型为 IDictionary<object, object>
的目标字典中? ?
if(type == typeof(IDictionary<,>))
{
// this doesn't compile
// value is passed into the method as object and must be cast
IDictionary<,> sourceDictionary = (IDictionary<,>)value;
IDictionary<object,object> targetDictionary = new Dictionary<object,object>();
// this doesn't compile
foreach (KeyValuePair<,> sourcePair in sourceDictionary)
{
targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
}
return targetDictionary;
}
编辑:
感谢到目前为止的回复。
这里的问题是 Copy 的参数只被称为“object”类型。例如:
public void CopyCaller(object obj)
{
if(obj.GetType() == typeof(IDictionary<,>)
Copy(dictObj); // this doesn't compile
}
最佳答案
也让您的方法通用化,然后您就可以做您正在做的事情了。您不必更改您的使用模式,因为编译器将能够从输入类型推断泛型类型。
public IDictionary<object, object> Copy(IDictionary<TKey, TValue> source)
{
IDictionary<object,object> targetDictionary = new Dictionary<object,object>();
foreach (KeyValuePair<TKey, TValue> sourcePair in sourceDictionary)
{
targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
}
return targetDictionary;
}
如果你真的不需要把它从IDictionary<TKey, TValue>
转换过来至 IDictionary<object, object>
那么你可以使用 Dictionary<TKey, TValue>
的复制构造函数它接受另一个字典作为输入并复制所有值——就像您现在所做的那样。
关于c# - 如何处理类型未知且无关紧要的通用字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2323802/