c# - 如何从方法返回 Action 类型

标签 c# c#-4.0

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

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/

相关文章:

c# - 序列化/反序列化为字符串 C#

c# - C#异步调用同步服务调用的策略

c# - 使用 Blazor 在 ASP.NET CORE 中更新数据库后如何刷新网页

c# - 将列表传递给任务

c# - 为什么 JSON.NET 在反序列化时不使用继承

xaml - 调整应用程序大小时显示消息

windows - 如何将位图图像保存到本地文件夹 Windows 应用商店应用程序

c# - 带有.net的Web服务无法连接到互联网信息服务中的mysql数据库

c# - 更新数组mongodb c#驱动程序中的字段

c# - Task.WaitAll 的阻塞等待