是否有一个简短的for循环版本,可以循环x次? [英] Is there a shorter/simpler version of the for loop to anything x times?
问题描述
通常,我们使用计数器执行for或while循环:
Usually we do something like a for or while loop with a counter:
for (int i = 0; i < 10; i++)
{
list.Add(GetRandomItem());
}
,但有时您会混为一谈.您可以改用while循环,但是如果您犯了一个错误,则该循环是无限的...
but sometimes you mix up with boundaries. You could use a while loop instead, but if you make a mistake this loop is infinite...
例如在Perl中,我会使用更明显的
In Perl for example I would use the more obvious
for(1..10){
list->add(getRandomItem());
}
是否有类似 doitXtimes(10){...}
的东西?
推荐答案
您可以轻松编写自己的扩展方法:
Well you can easily write your own extension method:
public static void Times(this int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
然后您可以编写:
10.Times(() => list.Add(GetRandomItem()));
我不确定我是否真的建议您这样做,但这是一个选择.我不相信框架中有类似的东西,尽管您可以使用 Enumerable.Range
或 Enumerable.Repeat
创建一个适当长度的惰性序列,该序列可以在某些情况下会很有用.
I'm not sure I'd actually suggest that you do that, but it's an option. I don't believe there's anything like that in the framework, although you can use Enumerable.Range
or Enumerable.Repeat
to create a lazy sequence of an appropriate length, which can be useful in some situations.
从C#6开始,使用 using static
指令导入静态方法,您仍然可以方便地访问静态方法而无需创建扩展方法.例如:
As of C# 6, you can still access a static method conveniently without creating an extension method, using a using static
directive to import it. For example:
// Normally in a namespace, of course.
public class LoopUtilities
{
public static void Repeat(int count, Action action)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
然后在您想使用它时:
using static LoopUtilities;
// Class declaration etc, then:
Repeat(5, () => Console.WriteLine("Hello."));
这篇关于是否有一个简短的for循环版本,可以循环x次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!