【发布时间】:2010-08-02 12:36:22
【问题描述】:
这是我的测试代码:
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 那样写第三行
- 为什么我必须编写 action("") 才能让它在 Do2 中工作
【问题讨论】:
-
我总是标记对我有帮助的回复。如果没有提供有用的解决方案,我不会标记它,直到我得到对我有帮助的答案。