Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.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# 类型为IEnumerable的参数<;IEnumerable<;字符串>&燃气轮机;接受列表<;列表<;字符串>&燃气轮机;而IEnumerable<;(int,IEnumerable<;string>;)>;不';T_C#_.net_Generics - Fatal编程技术网

C# 类型为IEnumerable的参数<;IEnumerable<;字符串>&燃气轮机;接受列表<;列表<;字符串>&燃气轮机;而IEnumerable<;(int,IEnumerable<;string>;)>;不';T

C# 类型为IEnumerable的参数<;IEnumerable<;字符串>&燃气轮机;接受列表<;列表<;字符串>&燃气轮机;而IEnumerable<;(int,IEnumerable<;string>;)>;不';T,c#,.net,generics,C#,.net,Generics,我有一节课 public class Test { public void M1(IEnumerable<IEnumerable<string>> p) { } public void M2(IEnumerable<(int, IEnumerable<string>)> p) { } } var t = new Test(); 类型为IEnumerable的参数接受List,而IEnumerable不接受List?它与 IEnum

我有一节课

public class Test
{
    public void M1(IEnumerable<IEnumerable<string>> p) { }
    public void M2(IEnumerable<(int, IEnumerable<string>)> p) { }
}
var t = new Test();
类型为
IEnumerable
的参数接受
List
,而
IEnumerable
不接受
List

它与

IEnumerable
是协变的,因此您可以分配一个更派生的T类型,一切都会很好=>
IEnumerable b=new List()

但是在您的情况下,
IEnumerable
IEnumerable
相同,并且因为
ValueTuple
不是
ValueTuple
的派生类型,所以您不能以这种方式使用它

更新感谢@JeppeStigNielsen


主要原因是协变不适用于值类型,C#7的新元组是值类型,而且
ValueType
在T2

中不协变。真正的原因是
IEnumerable
的协变在
T
为值类型时不适用。NET泛型中的协变和逆变对值类型不起作用。C#7的新元组是值类型。编辑:你给出的理由也是正确的!在
T2
中不协变。没有
结构
是协变的。
(int,IEnumerable)
值元组
类型。
var d1 = new List<List<string>> { new List<string>{ "test" } };
t.M1(d1);
var d2 = new List<(int, List<string>)> { (1, new List<string>{ "test" }) };
t.M2(d2);
var d2 = new List<(int, IEnumerable<string>)> { (1, new List<string>{ "test" }) };