我想知道为什么我不能直接转换(我有一个模糊的想法,这可能与协变/逆变的东西有关?),我是否被迫将第一本字典的元素复制到一个新的一个以获得我想要的类型?
最佳答案
您不能这样做,因为它们不是同一类型。考虑:
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>>
说 TValue
是List<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/