LoginSignup
3
2

More than 5 years have passed since last update.

C#によるRubyっぽい繰り返し

Posted at

Rubyを勉強して、10.times do~endを見たとき、C#でも使いたいなぁと思ったので、拡張メソッドで作ってみました。

public static class Extentions
{
    public static void For(this int i, Action action)
    {
        for(int j = 0; j < i; j++) {
            action();
        }
    }

    public static void For(this int i, Action<int> action)
    {
        for(int j = 0; j < i; j++) {
            action(j);
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        10.For(() => Console.WriteLine("for"));
        Console.WriteLine();
        10.For(i => Console.WriteLine(i));

        Console.Read();
    }

}

結果は以下の通り。

for
for
for
for
for
for
for
for
for
for

0
1
2
3
4
5
6
7
8
9
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2