ck.*_*ck. 5 c# generics dictionary
如果'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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:
感谢到目前为止的回复.
这里的问题是Copy的参数只被称为类型'object'.例如:
public void CopyCaller(object obj)
{
if(obj.GetType() == typeof(IDictionary<,>)
Copy(dictObj); // this doesn't compile
}
Run Code Online (Sandbox Code Playgroud)
让你的方法通用,然后你就能做你正在做的事情.您不必更改使用模式,因为编译器将能够从输入类型推断泛型类型.
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;
}
Run Code Online (Sandbox Code Playgroud)
如果你真的不需要将它转换IDictionary<TKey, TValue>为IDictionary<object, object>那么你可以使用复制构造,Dictionary<TKey, TValue>它接受另一个字典作为输入并复制所有值 - 就像你现在正在做的那样.
Pat*_*Pat -1
这可能适合您,但您需要 .net 3.5 或更高版本才能使用 var 关键字。
// this should compile
foreach (var sourcePair in sourceDictionary)
{
targetDictionary.Insert(sourcePair.Key, sourcePair.Value);
}
Run Code Online (Sandbox Code Playgroud)