参数类型“ void”不能分配给参数类型“ System.Action” [英] Argument type 'void' is not assignable to parameter type 'System.Action'
问题描述
这是我的测试代码:
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("");
}
}
前2个通话有效,但我想知道为什么第三个人没有。我不喜欢Do2中的代码,因为奇怪的是我在那里键入了 action()
类型,以便使其正常工作。
The first 2 calls work but I am wondering why the 3rd one does not. I do not fancy the code inside Do2 as it seems strange that I have type type action("")
in there in order to get it to work.
有人可以解释我不明白的两件事吗?
Could someone please explain the 2 things I do not understand please?
- 为什么我不能写第三行调用Do
- 为什么我必须编写action()才能使其在Do2中工作
推荐答案
dsufac.Do(WriteToConsoleWithSomethingExtra("Test"));
实际上首先调用该函数( WriteToConsoleWithSomethingExtra( Test)
),然后尝试将结果传递到 Do
中。由于没有结果( void
),所以不可能。
actually calls the function first (WriteToConsoleWithSomethingExtra("Test")
) and then attempts to pass the result into Do
. Since there is no result (void
), it's not possible.
您真正想要的是:
dsufac.Do(() => WriteToConsoleWithSomethingExtra("Test"));
内部声明一个不带任何内容的函数(()=>
位),在执行时调用 WriteToConsoleWithSomethingExtra( Test)
。 然后您的 dsufac.Do
呼叫将收到预期的操作。
The inner part declares a function that takes nothing (the () =>
bit), which calls WriteToConsoleWithSomethingExtra("Test")
when executed. Then your dsufac.Do
call will receive an action, like it expects.
至于 Do2
-您已经声明它采取了 Action< String>
,这意味着 action
是一个采用一个参数的函数。您必须将其传递一个字符串。该字符串可能为空,例如您的 action()
示例,或者它可能是从外部传递的,例如:
As for Do2
- you've declared it as taking Action<String>
, which means that action
is a function that takes one argument. You have to pass it a string. That string might be empty, like in your action("")
example, or it might be passed in externally, as in something like this:
dsufac.Do3(WriteToConsole, "Test");
...
internal void Do3(Action<String> action, String str)
{
action(str);
}
这篇关于参数类型“ void”不能分配给参数类型“ System.Action”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!