当我尝试编译以下代码时:
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>
?
最佳答案
想一想:
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
现在在那里!那不可能。这就是它不起作用的原因。
关于c# - 无法将 Dictionary List<string> 类型参数隐式转换为 ICollection<string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57307773/