我可以隐式地将 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?)
最佳答案
基本上,通用变体不适用于值类型。因此,虽然您可以
您需要将每个值装箱:
IEnumerable<IComparable> test3 = t2.Cast<IComparable>();
所以虽然这是有效的,因为 string
是引用类型:
List<string> strings = new List<string>();
IEnumerable<IComparable> comparables = strings;
... 等效项不适用于 List<int>
,你需要边走边装箱。
关于c# - List<int> 到 IEnumerable<IComparable>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15029198/