将 Ruby 的 times 方法转换为 C#

6

我正在尝试将Ruby中的time转换为C#,但现在卡住了。

以下是我的尝试:

public static class Extensions
{
    public static void Times(this Int32 times, WhatGoesHere?)
    {
        for (int i = 0; i < times; i++)
            ???
    }
}

我刚开始学习C#,也许这个问题很简单,我知道我想使用扩展方法。但由于在C#中函数不是'first class',所以我现在被卡住了。

那么,我应该使用什么参数类型来代替WhatGoesHere?

1个回答

5

您可以使用 Action 类型:

public static class Extensions
{
    public static void Times(this Int32 times, Action<Int32> action)
    {
        for (int i = 0; i < times; i++)
            action(i);
    }
}

class Program
{
    delegate void Del();

    static void Main(string[] args)
    {
        5.Times(Console.WriteLine);
        // or
        5.Times(i => Console.WriteLine(i));
    }
}

请点击这里了解委托。


谢谢!不知道代理(delegates)这个东西。 - user1443957

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接