如何处理类型未知且无关紧要的通用字典?

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)

Sam*_*eff 5

让你的方法通用,然后你就能做你正在做的事情.您不必更改使用模式,因为编译器将能够从输入类型推断泛型类型.

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)

  • @karbon,不,“var”不像使用“object”。`var` 就像显式指定完整类型一样,只是您不这样做,编译器会在**编译时**从代码中计算出它。`var` 对运行时代码的影响**零**。 (4认同)
  • `var` 是一种方便的方法,可以让编译器根据使用情况推断类型。这在上面使用的许多步骤中是不可能的,例如在“typeof()”检查或强制转换中。 (2认同)