Is there an “upto” method in C#?

前端 未结 6 1787
攒了一身酷
攒了一身酷 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:44

    Try this:

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

    With this you could write

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

    The function I wrote is called an extension method.
    At design time you notice is not a native function because it has a different icon.
    Estension methods are static methods or functions included in a static class and type they work on is the first param on which you must use this keyword.
    In IntExtensions class you could write all methods you please; grouping them inside the same static class makes you easy manage them.

提交回复
热议问题