我可以将int隐式转换为IComparable。我还可以将List或数组转换为IEnumerable。但是为什么不能将List隐式转换为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?)
List<T>
不支持类型协变,但是IEnumerable<T>
是支持的(从.NET 4开始)。类永远不能是协变的。在MSDN上搜索“泛型协变”以了解更多细节 :) - Jon Skeet