Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法隐式转换字典列表<;字符串>;ICollection的类型参数<;字符串>;_C#_.net_Dictionary_Generics_Types - Fatal编程技术网

C# 无法隐式转换字典列表<;字符串>;ICollection的类型参数<;字符串>;

C# 无法隐式转换字典列表<;字符串>;ICollection的类型参数<;字符串>;,c#,.net,dictionary,generics,types,C#,.net,Dictionary,Generics,Types,当我尝试编译以下代码时: Dictionary foo=newdictionary(); 我得到: CS0029: Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>' to 'System.Collections.Generic.Dictionary<string, System

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

Dictionary foo=newdictionary();
我得到:

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>>'
CS0029:无法将类型“System.Collections.Generic.Dictionary”隐式转换为“System.Collections.Generic.Dictionary”

List
实现
ICollection
时,为什么会出现此错误?

请思考一下:

Dictionary<string, ICollection<string>> foo 
哇。。。现在您要将该哈希集添加到字符串和列表的字典中吗?那怎么办?哈希集不是列表。好吧,这行不通。这就是为什么会出现错误


也许是一个更好的例子。假设狼和羊都实现了IAnimal

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

animals.Add("wolf", new Wolf());
字典动物=新字典();
添加(“狼”,新狼());

你的
词典
怎么了?现在那里会有一只狼!这不可能。这就是它不起作用的原因。

字典类型不同。仅仅因为这两个参数中的一个与另一个类型的参数中的一个存在继承关系,并不意味着字典之间存在这种关系。继承关系会影响字典值。您可以将
列表添加到
foo
,因为它接受实现
ICollection
的任何内容。这
foo[“a”]=新列表{“a”}工作如果您有一个ICollection,您可以添加Wolf和Sheep对象,因为当您将它们拉出时,您只能将它们用作IAnimal,它们都实现了IAnimal。我不明白为什么字典不同。
Dictionary<string, IAnimal> animals = new Dictionary<string, Sheep>();

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