我正在尝试找出如何从方法返回操作。我在网上找不到任何这样的例子。这是我尝试运行但失败的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
var testAction = test("it works");
testAction.Invoke(); //error here
Console.ReadLine();
}
static Action<string> test(string txt)
{
return (x) => Console.WriteLine(txt);
}
}
}
最佳答案
问题是textAction
是一个 Action<string>
,这意味着您需要传递一个字符串:
textAction("foo");
我怀疑你想要这样的东西:
class Program
{
static void Main(string[] args)
{
var testAction = test();
testAction("it works");
// or textAction.Invoke("it works");
Console.ReadLine();
}
// Don't pass a string here - the Action<string> handles that for you..
static Action<string> test()
{
return (x) => Console.WriteLine(x);
}
}
关于c# - 如何从方法返回 Action 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14758384/