如果「價值」是傳入通用字典,其類型是未知的/沒有關係,我該如何利用其條目,並付諸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;
}
編輯:
感謝到目前爲止的響應。
的這裏的問題是,參數複製僅稱爲類型「對象」。例如:
public void CopyCaller(object obj)
{
if(obj.GetType() == typeof(IDictionary<,>)
Copy(dictObj); // this doesn't compile
}
如果你使用'IDictionary'你弱類型的字典,而不是'的IDictionary <對象,對象>',你可以只需返回'詞典'。 –
2010-02-27 02:50:29
正如我在調用者的代碼無法控制我不能使用IDicitionary。 – 2010-02-27 12:56:06