您在 c# 中寻求解决方案,如果 f# 中的某些内容(afaik 这些语言可以“一起”使用)也受到赞赏,那么我可以为您提供以下片段(请注意,分隔不是您希望的分号,但是带空格):
函数 yourLoop 接受三个参数,两个整数:lowerBound upperBound 和一个函数(具有更具体的 'a -> unit 类型的副作用):body 的含义是
yourLoop (lowerBound:int) upperBound body
具有相同的效果
for i in lowerBound..upperBound do
body(i)
该函数如下所示:
let rec yourLoop (lowerBound:int) upperBound body =
if (lowerBound >= upperBound) then body upperBound
else
body lowerBound
yourLoop (lowerBound+1) upperBound body
例如,让它成为某个方法的主体
let something i = printfn "%s%i" "do something with " i
然后申请
yourLoop 0 5 something
产量
do something with 0
do something with 1
do something with 2
do something with 3
do something with 4
do something with 5
同样,如果你想自上而下循环,那么你可以写
let rec yourInvertedLoop lowerBound upperBound body =
if (lowerBound >= upperBound) then body lowerBound
else
body upperBound
yourInvertedLoop (lowerBound) (upperBound-1) body
屈服
yourInvertedLoop 0 5 something
do something with 5
do something with 4
do something with 3
do something with 2
do something with 1
do something with 0
对于更通用的功能,请考虑
let rec yourLoopIncr lowerBound upperBound next body =
if (next lowerBound >= upperBound) then body lowerBound
else
body lowerBound
yourLoopIncr (next lowerBound) upperBound next body
您可以在其中指定循环的迭代方式。例如,
yourLoopIncr 1 25 (fun x-> 2*x) something
会产生
do something with 1
do something with 2
do something with 4
do something with 8
do something with 16
备注:请注意,此解决方案仅适用于不返回值的主体。当然,您仍然可以在控制台上写东西或改变变量等。例如将代码
let mutable x = 0
let somethingElse n = x <- x+n
yourLoop 0 10 somethingElse
将 x 设置为值 55。