当我尝试编译以下代码时:
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>
时为什么出现此错误?
答案 0 :(得分:3)
想一想:
Dictionary<string, ICollection<string>> foo
这是string
和ICollection<string>
的字典。例如,您可以添加一对string
和HashSet<string>
,以实现ICollection<string>
。
= new Dictionary<string, List<string>>();
哇...现在,您要将HashSet添加到字符串和列表字典中吗?那将如何工作? HashSet不是列表。好吧,这行不通。这就是为什么您会出错。
也许是一个更好的例子。假设Wolf
和Sheep
都实现IAnimal
。
Dictionary<string, IAnimal> animals = new Dictionary<string, Sheep>();
animals.Add("wolf", new Wolf());
您的Dictionary<string, Sheep>
怎么了?现在将有一个Wolf
!那不可能。这就是为什么它不起作用。