gpt4 book ai didi

c# - 为什么LINQ操作会丢失集合的静态类型?

转载 作者:太空宇宙 更新时间:2023-11-03 17:34:23 25 4
gpt4 key购买 nike

无论我用作输入的收集类型如何,LINQ总是返回IEnumerable<MyType>而不是List<MyType>HashSet<MyType>

MSDN tutorial

int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// numQuery is an IEnumerable<int> <====== Why IEnumerable<int> instead of int[]?
var numQuery =
from num in numbers
where (num % 2) == 0
select num;


我想知道不保留集合类型(如元素类型)而不是建议的解决方法的背后的理由是什么。

我知道 toArraytoDictionarytoList存在,这不是问题。

编辑:C#中的实现与Scala有什么不同,它在不覆盖各地返回类型的情况下可以工作?

最佳答案

简短的回答:C#的类型系统太原始了,无法支持在更高阶的函数中保留集合类型(即没有代码重复)。

长答案:请参阅我的帖子here。 (实际上,它是关于Java的,但也适用于C#。)

关于c# - 为什么LINQ操作会丢失集合的静态类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6802360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com