這是我的測試代碼:參數類型「無效」是不能分配給參數類型「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("")
以便使其工作。
可能有人請解釋兩件事情我不明白嗎?
- 爲什麼,爲什麼我必須寫操作(「」),以便讓它在DO2
我始終標記的答覆,幫助我。如果沒有提供有用的解決方案,我不標記它,直到我得到幫助我的答案。 – 2010-08-02 12:43:43