问题描述
在C#中,使用.NET Framework 4,是否有一种优雅的方法可以重复执行相同的操作一定次数?例如,代替:
In C#, using .NET Framework 4, is there an elegant way to repeat the same action a determined number of times? For example, instead of:
int repeat = 10;
for (int i = 0; i < repeat; i++)
{
Console.WriteLine("Hello World.");
this.DoSomeStuff();
}
我想写些类似的东西:
Action toRepeat = () =>
{
Console.WriteLine("Hello World.");
this.DoSomeStuff();
};
toRepeat.Repeat(10);
或:
Enumerable.Repeat(10, () =>
{
Console.WriteLine("Hello World.");
this.DoSomeStuff();
});
我知道我可以为第一个示例创建自己的扩展方法,但是不存在一个已有的功能使其可以实现吗?
I know I can create my own extension method for the first example, but isn't there an existent feature which makes it already possible to do this?
推荐答案
没有内置的方法.
原因是C#本身试图在语言的功能性和命令性之间进行区分. C#仅在不产生副作用时才使函数编程变得容易.因此,您可以获得诸如LINQ的Where
,Select
等之类的集合操作方法,但是您不会得到ForEach
.
The reason is that C# as it is tries to enforce a divide between the functional and imperative sides of the language. C# only makes it easy to do functional programming when it is not going to produce side effects. Thus you get collection-manipulation methods like LINQ's Where
, Select
, etc., but you do not get ForEach
.
以类似的方式,您在此处尝试做的是找到一种表达本质上是当务之急的行为的功能方法.尽管C#为您提供了执行此操作的工具,但它并没有使您变得容易,因为这样做会使您的代码不清楚且不习惯.
In a similar way, what you are trying to do here is find some functional way of expressing what is essentially an imperative action. Although C# gives you the tools to do this, it does not try to make it easy for you, as doing so makes your code unclear and non-idiomatic.
有一个List<T>.ForEach
,但没有一个IEnumerable<T>.ForEach
.我要说List<T>.ForEach
的存在是一个历史产物,源于框架设计人员在.NET 2.0时代尚未考虑这些问题.在3.0中才需要进行清晰的划分.
There is a List<T>.ForEach
, but not an IEnumerable<T>.ForEach
. I would say the existence of List<T>.ForEach
is a historical artifact stemming from the framework designers not having thought through these issues around the time of .NET 2.0; the need for a clear division only became apparent in 3.0.
这篇关于是否有一种优雅的方式重复动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!