每次我需要在使用C#的算法中做N次我写这个代码
for (int i = 0; i < N; i++) { ... }
学习Ruby我已经学习了方法时间(),可以使用与此相同的语义
N.times do ... end
C#中的代码片段看起来更复杂,我们应该声明无用的变量i.
我试着编写返回IEnumerable的扩展方法,但我对结果不满意,因为我必须再次声明一个循环变量i.
public static class IntExtender { public static IEnumerable Times(this int times) { for (int i = 0; i < times; i++) yield return true; } } ... foreach (var i in 5.Times()) { ... }
是否可以使用一些新的C#3.0语言功能使N次循环更优雅?
一个稍微简短的cvk版本答案:
public static class Extensions { public static void Times(this int count, Action action) { for (int i=0; i < count; i++) { action(); } } public static void Times(this int count, Actionaction) { for (int i=0; i < count; i++) { action(i); } } }
使用:
5.Times(() => Console.WriteLine("Hi")); 5.Times(i => Console.WriteLine("Index: {0}", i));
使用C#3.0确实可以:
public interface ILoopIterator { void Do(Action action); void Do(Actionaction); } private class LoopIterator : ILoopIterator { private readonly int _start, _end; public LoopIterator(int count) { _start = 0; _end = count - 1; } public LoopIterator(int start, int end) { _start = start; _end = end; } public void Do(Action action) { for (int i = _start; i <= _end; i++) { action(); } } public void Do(Action action) { for (int i = _start; i <= _end; i++) { action(i); } } } public static ILoopIterator Times(this int count) { return new LoopIterator(count); }
用法:
int sum = 0; 5.Times().Do( i => sum += i );
从http://grabbagoft.blogspot.com/2007/10/ruby-style-loops-in-c-30.html无耻地偷走