是否存在这样的委托语法preferred超过拉姆达EX pression匿名方法呢?语法、拉姆、方法、在这样的

由网友(共你赴荣华)分享简介:随着像拉姆达EX pressions(内嵌code)的新功能的出现,是否意味着我们没有使用委托或匿名方法了吗?在几乎所有我见过的样本,它是使用新语法重写。With the advent of new features like lambda expressions (inline code), does it mea...

随着像拉姆达EX pressions(内嵌code)的新功能的出现,是否意味着我们没有使用委托或匿名方法了吗?在几乎所有我见过的样本,它是使用新语法重写。

With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.

在任何地方,我们仍然必须使用委托和lambda EX pressions将无法正常工作?

Any place where we still have to use delegates and lambda expressions won't work?

推荐答案

是有直接的地方使用匿名委托和lambda EX pressions将无法工作的地方。

Yes there are places where directly using anonymous delegates and lambda expressions won't work.

如果一个方法接受一个类型化的代表则编译器不知道该怎么解决匿名委托/λEX pression来,你会得到一个编译错误。

If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error.

public static void Invoke(Delegate d)
{
  d.DynamicInvoke();
}

static void Main(string[] args)
{
  // fails
  Invoke(() => Console.WriteLine("Test"));

  // works
  Invoke(new Action(() => Console.WriteLine("Test")));

  Console.ReadKey();
}

的code发生故障的线路将得到编译器错误无法转换拉姆达EX pression键入'System.Delegate',因为它不是一个委托类型。

The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".

阅读全文

相关推荐

最新文章