我在理解 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/