编程时,几乎本能地决定何时使用 for 循环或 foreach,但是选择使用 Enumerable.Range 的决定因素或问题空间是什么?
A For Loop当我们想要迭代一定次数(通过简单的数据类型)来计算/执行重复任务时选择。
A For Each类似,但是当我们想要迭代复杂对象列表以计算/执行重复任务时选择。
同样,使用 Enumerable.Range 的决定因素是什么?
IEnumerable<int> squares = Enumerable.Range(4, 3).Select(x => x * x);
foreach https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/foreach-in是关于迭代在现有的集合/集合上。
Enumerable.Range https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range is for 生成一组/集合。一般来说,你不会想写一个for https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/for循环只是为了生成一个集合(如果可以通过以下方式生成)Enumerable.Range https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range- 您只需编写更长的样板代码,并且需要您分配某种存储(例如List<int> https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1)首先填充。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)