【发布时间】:2010-02-24 05:05:21
【问题描述】:
如果 'value' 是传入的通用字典,其类型未知/无关紧要,我如何获取其条目并将它们放入 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 的参数仅称为类型“对象”。例如:
public void CopyCaller(object obj)
{
if(obj.GetType() == typeof(IDictionary<,>)
Copy(dictObj); // this doesn't compile
}
【问题讨论】:
-
如果您将
IDictionary用于弱类型字典而不是IDictionary<object, object>,则只需返回Dictionary<T,K>。 -
我无法使用 IDicitionary,因为我无法控制调用者的代码。
标签: c# generics dictionary