C# 中的高阶函数 which return void

High order functions in C# which return void

我在理解 C# 中的 HOF 时遇到一些问题。我希望我的 DoSomething 函数接收一个函数作为参数 returns void 并接收 两个字符串 。正如编译器所抱怨的那样,我无法将第一个通用参数设置为 void。这给了我一个错误。

在 C# 中执行此操作的正确语法是什么?

using System.IO;
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
        DoSomething((v1, v2) => Console.WriteLine(v1, v2));
    }
    
    private static void DoSomething(Func<string,string,string> f){
        f("1", "2");
    }
}

基本上使用Action<string, string>而不是Func<string, string, string>Action 代表声明为 return voidFunc 委托声明为 return“最终类型参数”。

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello, World!");
        DoSomething((v1, v2) => Console.WriteLine(v1, v2));
    }

    private static void DoSomething(Action<string, string> action)
    {
        action("1", "2");
    }
}

请注意,这里的结果只是“1”,因为它被解释为格式字符串。如果您改用 action("Value here: '{0}'", "some-value");,您将获得 Value here: 'some-value'.

的输出