Is there an “upto” method in C#?

前端 未结 6 1768
攒了一身酷
攒了一身酷 2021-02-18 14:31

Here\'s a bit of code which prints out the squares of the numbers from 0 to 9:

for (int i = 0; i < 10; i++)
    Console.WriteLine(i*i);

Doin

6条回答
  •  一生所求
    2021-02-18 15:07

    Make your method like this in a static class "Extensions" for example:

    public static void UpTo(this int n, Action proc)
    {
        for (var i = 0; i < n; i++)
            proc(i);
    }
    

    And the usage:

    var n = 10;
    n.UpTo(i => Console.WriteLine(i * i));
    

    Hope this helps! :)

提交回复
热议问题