![](/img/trans.png)
[英]When would you use a List<KeyValuePair<T1, T2>> instead of a Dictionary<T1, T2>?
[英]Why can't Dictionary<T1, List<T2>> be cast to Dictionary<T1, IEnumerable<T2>>?
我想知道为什么我不能只进行转换(我有一个模糊的想法,这可能与协方差/共变量有关?),我是否被迫将第一个字典的元素复制到一个新的字典中?得到我想要的类型?
您不能这样做,因为它们不是同一类型。 考虑:
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>
作为值Add()
。 如果可以将其强制转换为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>
因为后者将允许您添加猫,松鼠等。
您无法进行强制转换,因为它仍然是Dictionary<T1, List<T2>>
可以说
Dictionary<string, List<int>> d1 = new Dictionary<string, List<int>>();
Dictionary<string, IEnumerable<int>> d2 = (Dictionary<string, IEnumerable<int>>)d1; // this is the invalid cast
d2["one"] = new int[0]; // valid for d2
List<int> list1 = d1["one"]; // would fail
是的,这是协方差的问题。 我相信这已被.net 4.0纠正
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.