C#中返回void的高阶函数

Mat*_*ios 2 c# higher-order-functions

我在理解 C# 中的 HOF 时遇到了一些问题。我希望我的 DoSomething 函数接收一个函数作为参数,该函数返回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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

使用Action<string, string>而不是Func<string, string, string>基本。在Action代表们宣布回归void; 该Func代表声明以返回“最后的类型参数”。

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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