用Enumerable.Range与传统for循环的foreach思考 [英] Thoughts on foreach with Enumerable.Range vs traditional for loop
问题描述
//写数字1到7
foreach(Enumerable.Range(1,7)中的int索引)
{
Console.WriteLine(index);
超过传统的for循环:
//编写数字1到7
(int index = 1; index <= 7; index ++)
{
Console.WriteLine(index);
$ b假设'n'很小,所以表现不是问题,有没有人反对到传统风格的新风格?解决方案我发现后者的最小到最大格式比为此,范围
的最小计数风格。另外,我认为从一个不是更快,更短,更不熟悉,也不明显更清晰的标准这样的改变是不是一个好习惯。
那就是说,我一般不反对这个想法。如果你的语法看起来像 foreach(int x从1到8)
,那么我可能会认为这会比 for
循环。但是, Enumerable.Range
非常笨重。
In C# 3.0, I'm liking this style:
// Write the numbers 1 thru 7
foreach( int index in Enumerable.Range( 1, 7 ) )
{
Console.WriteLine( index );
}
over the traditional for loop:
// Write the numbers 1 thru 7
for( int index = 1; index <= 7; index++ )
{
Console.WriteLine( index );
}
Assuming 'n' is small so performance is not an issue, does anyone object to the new style over the traditional style?
解决方案 I find the latter's "minimum-to-maximum" format a lot clearer than Range
's "minimum-count" style for this purpose. Also, I don't think it's really a good practice to make a change like this from the norm that is not faster, not shorter, not more familiar, and not obviously clearer.
That said, I'm not against the idea in general. If you came up to me with syntax that looked something like foreach (int x from 1 to 8)
then I'd probably agree that that would be an improvement over a for
loop. However, Enumerable.Range
is pretty clunky.
这篇关于用Enumerable.Range与传统for循环的foreach思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!