C# 列表<;int>;到IEnumerable<;i可比较>;

C# 列表<;int>;到IEnumerable<;i可比较>;,c#,list,ienumerable,icomparable,C#,List,Ienumerable,Icomparable,我可以隐式地将int转换为IComparable。我还可以将列表或数组强制转换为IEnumerable 但是为什么我不能隐式地将列表转换为IEnumerable呢 我用.net framework 4.5和Visual Studio 2012 Ultimate对此进行了测试 要测试的代码: IComparable test1; int t1 = 5; test1 = t1; //OK IEnumerable<int> test2; List<int> t2 = new

我可以隐式地将int转换为IComparable。我还可以将列表或数组强制转换为IEnumerable

但是为什么我不能隐式地将列表转换为IEnumerable呢

我用.net framework 4.5和Visual Studio 2012 Ultimate对此进行了测试

要测试的代码:

IComparable test1;
int t1 = 5;
test1 = t1; //OK

IEnumerable<int> test2;
List<int> t2 = new List<int>();
int[] t3 = new int[] { 5, 6 };
test2 = t2; //OK
test2 = t3; //OK

TabAlignment[] test;

IEnumerable<IComparable> test3;
test3 = t2; //error Cannot implicitly convert type 'System.Collections.Generic.List<int>' to 'System.Collections.Generic.IEnumerable<System.IComparable>'. An explicit conversion exists (are you missing a cast?)
i可比较测试1;
int t1=5;
test1=t1//好啊
IEnumerable test2;
列表t2=新列表();
int[]t3=新的int[]{5,6};
test2=t2//好啊
test2=t3//好啊
TabAlignment[]试验;
IEnumerable test3;
test3=t2//错误无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.IEnumerable”。存在显式转换(是否缺少强制转换?)

一般差异基本上不适用于值类型。所以当你可以的时候

您需要对每个值进行框选:

IEnumerable<IComparable> test3 = t2.Cast<IComparable>();

。。。等价物不适用于
列表
,您需要边走边装箱。

它与泛型列表是一种常见的混淆,但基本上如果您对其进行概括,它会更有意义:

考虑以下设置:

public interface IA{
}

public class A : IA{
}

var listA = new List<A>();
所以在你的情况下你可以

test3 = t2.Cast<IComparable>();
test3=t2.Cast();

阅读了您的答案并与我的答案进行了比较(然后在代码中进行了测试),我意识到我的答案在本例中是错误的,因为它处理的是列表->列表而不是列表->IEnumerable的转换,但我不明白为什么会有不同。你能解释一下吗?@JonEgerton:我怀疑你在评论中加入了泛型类型参数,但我看不到它们。请再试一次,在与代码相关的位上打勾。@JonEgerton:好的,请通读您的答案,然后再看一次您的评论…-这是因为
List
t
中不是协变的,但是
IEnuemrable
是协变的(从.NET 4开始)。类永远不能是变量。在MSDN上搜索“通用差异”以了解更多详细信息:)我想我知道了,但我会跟进它-感谢您的反馈。
List<IA> listI = ListA;
listI = ListA.Cast<IA>();
test3 = t2.Cast<IComparable>();