是否存在这样的委托语法preferred超过拉姆达EX pression匿名方法呢? [英] Is there a case where delegate syntax is preferred over lambda expression for anonymous methods?

查看:132
本文介绍了是否存在这样的委托语法preferred超过拉姆达EX pression匿名方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着像拉姆达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".

这篇关于是否存在这样的委托语法preferred超过拉姆达EX pression匿名方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆