c# - 为什么不能将 Dictionary<T1, List<T2>> 转换为 Dictionary<T1, IEnumerable<T2>>?

标签 c# .net generics collections casting

我想知道为什么我不能直接转换(我有一个模糊的想法,这可能与协变/逆变的东西有关?),我是否被迫将第一本字典的元素复制到一个新的一个以获得我想要的类型?

最佳答案

您不能这样做,因为它们不是同一类型。考虑:

        var x = new Dictionary<string, List<int>>();

        // won't compile, but assume it could...
        Dictionary<string, IEnumerable<int>> xPrime = x;

        // uh oh, would allow us to legally add array of int!
        xPrime["Hi"] = new int[13];

这有意义吗?因为Dictionary<string, List<int>>TValueList<int>这意味着你可以 Add()一个List<int>作为一个值。如果您可以将其转换为 Dictionary<string, IEnumerable<int>>这意味着值类型是 IEnumerable<int>这意味着你可以 Add() 任何 IEnumerable<int> ( int[]HashSet<int> 等)会违反原始类型。

所以,一个 List<T>可以转换为 IEnumerable<T>引用因为 List<T>工具 IEnumerable<T> ,但这并不意味着 Dictionary<TKey, List<TValue>>实现/扩展 Dictionary<TKey, IEnumerable<TValue>> .

更简单地说:

Dictionary<int, Dog> 

无法转换为

Dictionary<int, Animal>

因为后者允许您添加 Cat、Squirrel 等。

关于c# - 为什么不能将 Dictionary<T1, List<T2>> 转换为 Dictionary<T1, IEnumerable<T2>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8734272/

相关文章:

c# - .NET EventHandlers - 是否通用?

c# - 发送参数后异步等待事件

.net - 如何一次性将多个目标从3.5升级到4.0的项目(相同的解决方案)?

java - 从传递的参数将对象转换为类

java - 是否可以在没有条件语句的情况下创建具有相同父类的随机对象?

c# - Linq 其中值在数组中

c# - 我如何定义一个检查整数列表

c# - 将时间跨度格式化为 TotalMilliseconds

c# - .NET 设计 View 不运行 Windows 窗体 OnLoad

swift - Generic Decodable 停止使用 swift 4.1