有没有一种方法可以多次调用方法/代码行而不使用for/foreach/while循环?
例如,如果我用于循环:
int numberOfIterations = 6;
for(int i = 0; i < numberOfIterations; i++)
{
DoSomething();
SomeProperty = true;
}
Run Code Online (Sandbox Code Playgroud)
我正在调用的代码行不使用'i',在我看来,整个循环声明隐藏了我正在尝试做的事情.对于foreach来说这是一样的.
我想知道是否有一个我可以使用的循环语句看起来像:
do(6)
{
DoSomething();
SomeProperty = true;
}
Run Code Online (Sandbox Code Playgroud)
很明显,我只想执行该代码6次,并且没有涉及索引实例化和向某个任意变量添加1的噪声.
作为一个学习练习,我编写了一个静态类和方法:
Do.Multiple(int iterations, Action action)
Run Code Online (Sandbox Code Playgroud)
哪个有效,但在自命不凡的规模上得分非常高,我相信我的同行不会赞同.
我可能只是挑剔而且for循环肯定是最容易识别的,但作为一个学习点我只是想知道是否有(更清洁)替代方案.谢谢.
(我看了一下这个线程,但它不是很一样) 使用的IEnumerable没有foreach循环
Jon*_*eet 10
通过将其作为扩展方法,您可以在预扩展比例上得分更高:
public static void Times(this int iterations, Action action)
{
for (int i = 0; i < iterations; i++)
{
action();
}
}
...
6.Times(() => {
DoSomething();
SomeProperty = true;
});
Run Code Online (Sandbox Code Playgroud)
但我肯定会坚持for循环.这是惯用的,公认的做法.