c# - C# 中返回 void 的高阶函数

标签 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");
    }
}

最佳答案

使用 Action<string, string>而不是 Func<string, string, string>基本上。 Action声明代表返回 void ; Func委托(delegate)被声明为返回“最终类型参数”。

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' 的输出.

关于c# - C# 中返回 void 的高阶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64030783/

相关文章:

c# - System.Security.Cryptography.KeyDerivation 未在 VS Community 2015 版本中被识别。 14.0.2

c# - Azure 到 Dynamics CRM 2011 : how to implement AD authentication?

powershell - 选择/映射 Powershell 数组的每一项到新数组

scala - 与 Scala 中的 'lifting' 函数混淆

c# - 重命名高阶列表操作背后的基本原理

c# - 为模板动态创建通用类型

c# - 在新的 AppDomain 中启动 WCF 服务以启用卷影复制(Windows 服务托管)

c# - 查找首字母大写且组合在一起的单词

javascript - 一种扁平化对象的优雅方式

haskell - 为什么 Haskell 在函数组合后不接受参数?