Is there an “upto” method in C#?

前端 未结 6 1770
攒了一身酷
攒了一身酷 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 14:40

    Turn it into an extension method (note the this before the n parameter, which defines the type this method operates on):

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

    Usage:

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

    Note: The above method call isn't particularly intuitive though. Remember code is written once and read many times.

    Maybe allowing something like below might be slightly better, but to be honest i'd still just write a foreach loop.

    0.UpTo(10 /*or 9 maybe*/, (i) => Console.WriteLine(i * i));
    

    If you wanted this, then you could write an extension method like this:

    public static void UpTo(this int start, int end, Action proc)
    {
        for (int i = start; i < end; i++)
            proc(i);
    }
    

    Change < to <= if you want an inclusive upper bound.

提交回复
热议问题