c# - List<int> 到 IEnumerable<IComparable>

标签 c# list ienumerable icomparable

我可以隐式地将 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/

相关文章:

C# 2015 - Gridview 选定的行到 RDLC 报告 - 每页一行

c# - 在方法中修改变量是不好的做法吗?

Python:为什么列表没有查找方法?

list - 从列表中复制第 n 个值

c# - 两个列表之间的 "Left XOR"LINQ

c# - Unity Raycast() 和 DrawRay() 使用相同的输入创建不同的光线

list - SML:如何向函数传递一个列表并返回删除所有负实数的列表?

c# - 将带有 List 的字典转换为 IEnumerable

c# - IEnumerable IEnumerator 带或不带 Current moveNext 重置

c# - 创建对象的命名标准是什么?