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

标签 c# generics dictionary

如果“值”是一个传入的通用字典,其类型未知/无关紧要,我如何获取它的条目并将它们放入类型为 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/

相关文章:

c# - 返回一个通用的隐式引用

python - 如何使用 3 个列表在 Python 中创建嵌套字典

c# - 异步创建文件

c# - 扩展方法必须在非泛型静态类中定义

C# 对 SSPI 的调用失败,请参阅内部异常 - 无法联系本地安全机构

python - 如何将列名与字典键匹配并向计数器添加值

python - 使用字典过滤 pandas 数据框的列值

c# - 无法将数据设置到列表中然后打印。

c# - 泛型或多个类

json - 如何在 Dart 中使用带有 json 序列化的泛型和泛型列表?