这是我的测试代码:
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("");
}
}
前两个调用可以工作,但我想知道为什么第三个调用不行。我不喜欢Do2内部的代码,因为似乎需要在其中使用action("")
类型才能使其正常工作。
请问有人能解释一下我不理解的两件事吗?
- 为什么我不能像第三行那样调用Do。
- 为什么我必须在Do2中写入action("")才能使它正常工作。