相关疑难解决方法(0)

参数类型'System.Action'不能赋予参数类型'void'

这是我的测试代码:

class PassingInActionStatement
{
    static void Main(string[] args)
    {
        var dsufac = new DoSomethingUsefulForAChange();

        dsufac.Do(WriteToConsole);
        dsufac.Do2(s => WriteToConsoleWithSomethingExtra("Test"));
        dsufac.Do(WriteToConsoleWithSomethingExtra("Test")); // Does not compile
    }

    internal static void WriteToConsole()
    {
        Console.WriteLine("Done");
    }

    internal static void WriteToConsoleWithSomethingExtra(String input)
    {
        Console.WriteLine(input);
    }
}

internal class DoSomethingUsefulForAChange
{
    internal void Do(Action action)
    {
        action();
    }

    internal void Do2(Action<String> action)
    {
        action("");
    }
}
Run Code Online (Sandbox Code Playgroud)

前2个电话有效,但我想知道为什么第3个电话没有.我不喜欢Do2中的代码,因为我action("")在那里有类型类型以使其工作似乎很奇怪.

有人可以解释一下我不明白的两件事吗?

  1. 为什么我不能通过调用Do来编写第三行
  2. 为什么我必须写动作("")才能让它在Do2中工作

c# c#-3.0

16
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×1

c#-3.0 ×1