C# 为什么可以';我不能通过列表<;列表<;Foo>&燃气轮机;到IEnumerable<;IEnumerable<;Foo>&燃气轮机;

C# 为什么可以';我不能通过列表<;列表<;Foo>&燃气轮机;到IEnumerable<;IEnumerable<;Foo>&燃气轮机;,c#,generics,.net-3.5,C#,Generics,.net 3.5,此代码生成两个编译时错误: private void DoSomething() { List<List<Foo>> myFoos = GetFoos(); UseFoos(myFoos); } private void UseFoos(IEnumerable<IEnumerable<Foo>>) { } private void DoSomething() { List myFoos=GetFoos(); UseFoos(

此代码生成两个编译时错误:

private void DoSomething()
{
    List<List<Foo>> myFoos = GetFoos();

    UseFoos(myFoos);
}

private void UseFoos(IEnumerable<IEnumerable<Foo>>)
{

}
private void DoSomething()
{
List myFoos=GetFoos();
UseFoos(myFoos);
}
私有void UseFoos(IEnumerable)
{
}
与“NameSpace.Class.UseFoos(System.Collections.Generic.IEnumerable)”匹配的最佳重载方法具有一些无效参数

参数1:无法从“System.Collections.Generic.List”转换为“System.Collections.Generic.IEnumerable”


转换为
IEnumberable
不是问题。强制转换失败类型的内部
列表
组件有什么不同?

编辑:我刚刚意识到我还没有真正回答如何绕过限制的问题。幸运的是,这很容易:

UseFoos(myFoos.Cast<IEnumerable<Foo>>());
请注意,即使在C#4中,类也不是不变的,因此这不起作用:

// This won't work
List<string> strings = new List<string>();
List<object> objects = strings;
//这行不通
列表字符串=新列表();
列出对象=字符串;
。。。即使对于接口,也只有在安全的情况下才支持:

// This won't work either
IList<string> strings = new List<string>();
IList<object> objects = strings;
//这也不行
IList strings=新列表();
IList对象=字符串;
接口(或委托)必须声明类型参数本身的差异,因此如果您查看.NET4,您将看到它被声明为

public interface IEnumerable<out T>
公共接口IEnumerable
其中
out
T
中声明协方差


Eric Lippert在他的博客类别中有更多关于这方面的内容。

你是C#4.0之前的吗?如果不是完全重复的话,也可能是相关的。你确定你使用的是C#4.0吗?@AakashM:正确,我使用的是3.5。@AakashM正在查看这些示例中的3.5变通方法;除非/直到我真的需要支持内部容器不是
列表
我想我会通过。这些实现都需要进行丑陋性和明显性检查。
public interface IEnumerable<out T>