无法将Dictionary List <string>类型参数隐式转换为ICollection <string>

时间:2019-08-01 11:14:23

标签: c# .net dictionary generics types

当我尝试编译以下代码时:

Dictionary<string, ICollection<string>> foo = new Dictionary<string, List<string>>();

我得到:

CS0029: Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>' to 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.ICollection<string>>'

List<string>实现ICollection<string>时为什么出现此错误?

1 个答案:

答案 0 :(得分:3)

想一想:

Dictionary<string, ICollection<string>> foo 

这是stringICollection<string>的字典。例如,您可以添加一对stringHashSet<string>,以实现ICollection<string>

= new Dictionary<string, List<string>>();

哇...现在,您要将HashSet添加到字符串和列表字典中吗?那将如何工作? HashSet不是列表。好吧,这行不通。这就是为什么您会出错。


也许是一个更好的例子。假设WolfSheep都实现IAnimal

Dictionary<string, IAnimal> animals = new Dictionary<string, Sheep>();

animals.Add("wolf", new Wolf());

您的Dictionary<string, Sheep>怎么了?现在将有一个Wolf!那不可能。这就是为什么它不起作用。