如何从一个方法中返回一个操作类型

4

我正在尝试找出如何从一个方法中返回一个操作。我在网上找不到任何例子。这是我尝试运行但失败的代码:

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);
        }
    }
}

2
你需要将参数传递给调用,而不是作为声明的一部分。 - Brian Rasmussen
4个回答

4
问题在于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);
    }
}

2
我怀疑 test 是试图柯里化 WriteLine,因此他实际上希望它返回 Action 而不是使 test 无参数。虽然由于问题的含糊不清,两种解释都是可能的。 - Servy
@Servy 说得好 - 这可能是目标,但没有明确说明,所以很难确定。 - Reed Copsey

3
你需要返回一个接受 string 参数的操作。当你调用该操作时,需要提供该参数:

testAction("hello world");

当然,您的操作忽略了该参数,因此更恰当的修复方法是更改操作,使其不接受任何参数:

static Action test(string txt)
{
    return () => Console.WriteLine(txt);
}

现在您的程序将按预期运行。

2

因为你拥有的是一个 Action<String>,所以你的调用需要包括你要执行的字符串。

testAction.Invoke("A string");

应该可以工作


1
你想创建的操作应该没有参数,这样你就可以不用提供参数直接调用它。因此,更改test的返回类型,并且删除你声明但从未使用过的x
    static Action test(string txt)
    {
        return () => Console.WriteLine(txt);
    }

然后调用代码将正常工作:
        var testAction = test("it works"); // store the string in txt
        testAction.Invoke();
        Console.ReadLine();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接