最后一个语句无法编译。请参阅评论以及代码以了解我的问题。
class Test
{
private static void Foo(Delegate d){}
private static void Bar(Action a){}
static void Main()
{
Foo(new Action(() => { Console.WriteLine("a"); })); // Action converts to Delegate implicitly
Bar(() => { Console.WriteLine("b"); }); // lambda converts to Action implicitly
Foo(() => { Console.WriteLine("c"); }); // Why doesn't this compile ? (lambda converts to Action implicitly, and then Action converts to Delegate implicitly)
}
}
答案 0 :(得分:4)
因为.net编译器不知道将lambda转换为什么类型的委托。它可以是一个Action,也可以是void MyDelegate()
。
如果按如下方式进行更改,则应该有效:
Foo(new Action(() => { Console.WriteLine("c"); }));
答案 1 :(得分:1)
为什么编译器应该知道如何分两步:来自lambda - >行动 - >委派?
编译:
class Test
{
private static void Foo(Delegate d) { }
private static void Bar(Action a) { }
static void Main()
{
Foo(new Action(() => { Console.WriteLine("world2"); })); // Action converts to Delegate implicitly
Bar(() => { Console.WriteLine("world3"); }); // lambda converts to Action implicitly
Foo((Action)(() => { Console.WriteLine("world3"); })); // This compiles
}
}