C# 对于匿名方法,是否存在委托语法优于 lambda 表达式的情况?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/106324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a case where delegate syntax is preferred over lambda expression for anonymous methods?
提问by dragon
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 表达式(内联代码)等新功能的出现,是否意味着我们不再需要使用委托或匿名方法?在我见过的几乎所有示例中,它都是使用新语法重写的。
Any place where we still have to use delegates and lambda expressions won't work?
我们仍然必须使用委托和 lambda 表达式的任何地方都不起作用?
回答by Darren Kopp
lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods signature. you can just do this:
lambda 是匿名委托的快捷方式,但您将始终使用委托。委托指定方法签名。你可以这样做:
delegate(int i) { Console.WriteLine(i.ToString()) }
can be replaced with
可以替换为
f => Console.WriteLine(f.ToString())
回答by Martin C.
Lambda expressions are just "syntactic sugar", the compiler will generate appropriate delegates for you. You can investigate this by using Lutz Roeder's Reflector.
Lambda 表达式只是“语法糖”,编译器会为您生成合适的委托。您可以使用 Lutz Roeder 的 Reflector 对此进行调查。
回答by sontek
Lamda's are just syntactic sugar for delegates, they are not just inline, you can do the following:
Lamda 只是代表的语法糖,它们不仅仅是内联的,您可以执行以下操作:
s.Find(a =>
{
if (a.StartsWith("H"))
return a.Equals("HI");
else
return !a.Equals("FOO");
});
And delegates are still used when defining events, or when you have lots of arguments and want to actually strongly type the method being called.
当定义事件时,或者当你有很多参数并且想要真正强类型被调用的方法时,仍然使用委托。
回答by James Newton-King
Yes there are places where directly using anonymous delegates and lambda expressions won't work.
是的,有些地方直接使用匿名委托和 lambda 表达式是行不通的。
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.
如果方法采用无类型委托,则编译器不知道将匿名委托/lambda 表达式解析为什么,您将收到编译器错误。
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();
}
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".
失败的代码行将得到编译器错误“无法将 lambda 表达式转换为类型 'System.Delegate',因为它不是委托类型”。
回答by JacquesB
Delegate have two meanings in C#.
委托在 C# 中有两种含义。
The keyword delegate
can be used to define a function signature type. This is usually used when defininge the signature of higher-order functions, i.e. functions that take other functions as arguments. This use of delegate is still relevant.
关键字delegate
可用于定义函数签名类型。这通常用于定义高阶函数的签名,即以其他函数作为参数的函数。委托的这种使用仍然相关。
The delegate
keyword can also be used to define an inline anonymous function. In the case where the function is just a single expression, the lambda syntax is a simpler alternative.
该delegate
关键字还可用于定义内联匿名函数。在函数只是单个表达式的情况下,lambda 语法是一种更简单的替代方法。
回答by Dandikas
Lambda expression is not (and was not meant to be) a silver bullet that would replace (hide) delegates. It is great with small local things like:
Lambda 表达式不是(也不应该是)替代(隐藏)代表的灵丹妙药。它非常适合小型本地事物,例如:
List<string> names = GetNames();
names.ForEach(Console.WriteLine);
- it makes code more readable thus simple to understand.
- It makes code shorter thus less work for us ;)
- 它使代码更具可读性,因此易于理解。
- 它使代码更短,因此对我们来说工作更少;)
On the other hand it is very simple to misuse them. Long or/and complex lambda expressions are tending to be:
另一方面,滥用它们非常简单。长或/和复杂的 lambda 表达式往往是:
- Hard to understand for new developers
- Less object oriented
- Much harder to read
- 新开发人员难以理解
- 较少面向对象
- 更难阅读
So “does it mean we don't have to use delegates or anonymous methods anymore?” No – use Lambda expression where you win time/readability otherwise consider using delegates.
那么“这是否意味着我们不必再使用委托或匿名方法了?” 否 - 在您赢得时间/可读性的地方使用 Lambda 表达式,否则考虑使用委托。
回答by nawfal
One not so bigadvantage for the older delegate
syntax is that you need not specify the parameters if you dont use it in the method body. From msdn
旧语法的一个不那么大的优势delegate
是,如果您不在方法主体中使用它,则无需指定参数。来自msdn
There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.
在一种情况下,匿名方法提供了 lambda 表达式中没有的功能。匿名方法使您能够省略参数列表。这意味着匿名方法可以转换为具有各种签名的委托。这对于 lambda 表达式是不可能的。
For example you can do:
例如你可以这样做:
Action<int> a = delegate { }; //takes 1 argument, but not specified on the RHS
While this fails:
虽然这失败了:
Action<int> a = => { }; //omitted parameter, doesnt compile.
This technique mostly comes handy when writing event-handlers, like:
这种技术在编写事件处理程序时通常会派上用场,例如:
button.onClicked += delegate { Console.WriteLine("clicked"); };
This is not a strongadvantage. It's better to adopt the newer syntax always imho.
这不是一个强大的优势。最好总是采用较新的语法恕我直言。