我已经快速阅读了Microsoft Lambda表达式文档。
不过,这样的例子帮助我更好地理解:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
不过,我还是不明白为什么这是一种创新。它只是一个在“方法变量”结束时死亡的方法,对吧?为什么我要用这个而不是真正的方法?
我已经快速阅读了Microsoft Lambda表达式文档。
不过,这样的例子帮助我更好地理解:
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
不过,我还是不明白为什么这是一种创新。它只是一个在“方法变量”结束时死亡的方法,对吧?为什么我要用这个而不是真正的方法?
当前回答
很多时候,您只在一个地方使用功能,所以创建方法只会使类变得混乱。
其他回答
很多时候,您只在一个地方使用功能,所以创建方法只会使类变得混乱。
The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework.
此外,由于它们描述的是一次性使用的代码,所以它们不必是类的成员,这样会导致代码更加复杂。想象一下,每当我们想要配置类对象的操作时,都必须声明一个焦点不明确的类。
创新在于类型的安全性和透明度。虽然您没有声明lambda表达式的类型,但它们是推断出来的,并且可以由代码搜索、静态分析、重构工具和运行时反射使用。
例如,在您使用SQL之前,可能会受到SQL注入攻击,因为黑客在通常需要数字的地方传递了一个字符串。现在您将使用LINQ lambda表达式,这是受保护的。
在纯委托上构建LINQ API是不可能的,因为它需要在计算表达式树之前将它们组合在一起。
2016年,大多数流行语言都支持lambda表达式,c#是主流命令式语言中这一演变的先驱之一。
这只是使用lambda表达式的一种方式。你可以在任何可以使用委托的地方使用lambda表达式。这允许你做这样的事情:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
strings.Find(s => s == "hello");
这段代码将在列表中搜索与单词“hello”匹配的条目。另一种方法是传递一个委托给Find方法,像这样:
List<string> strings = new List<string>();
strings.Add("Good");
strings.Add("Morning")
strings.Add("Starshine");
strings.Add("The");
strings.Add("Earth");
strings.Add("says");
strings.Add("hello");
private static bool FindHello(String s)
{
return s == "hello";
}
strings.Find(FindHello);
编辑:
在c# 2.0中,这可以使用匿名委托语法完成:
strings.Find(delegate(String s) { return s == "hello"; });
Lambda明显地清理了语法。
Lambda清理了c# 2.0的匿名委托语法…例如
Strings.Find(s => s == "hello");
在c# 2.0中是这样完成的:
Strings.Find(delegate(String s) { return s == "hello"; });
在功能上,它们做的是完全相同的事情,只是语法更简洁。