我已经快速阅读了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
不过,我还是不明白为什么这是一种创新。它只是一个在“方法变量”结束时死亡的方法,对吧?为什么我要用这个而不是真正的方法?
当前回答
lambda表达式就像代替委托实例编写的匿名方法。
delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;
考虑lambda表达式x => x * x;
输入参数值为x(在=>的左边) 函数逻辑为x * x(在=>的右侧)
lambda表达式的代码可以是语句块,而不是表达式。
x => {return x * x;};
例子
注意:Func是一个预定义的泛型委托。
Console.WriteLine(MyMethod(x => "Hi " + x));
public static string MyMethod(Func<string, string> strategy)
{
return strategy("Lijo").ToString();
}
参考文献
委托和接口如何可以互换使用?
其他回答
这可能是关于为什么使用lambda表达式的最好解释-> https://youtu.be/j9nj5dTo54Q
总之,这是为了提高代码的可读性,通过重用而不是复制代码来减少错误的机会,并利用发生在幕后的优化。
lambda表达式就像代替委托实例编写的匿名方法。
delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;
考虑lambda表达式x => x * x;
输入参数值为x(在=>的左边) 函数逻辑为x * x(在=>的右侧)
lambda表达式的代码可以是语句块,而不是表达式。
x => {return x * x;};
例子
注意:Func是一个预定义的泛型委托。
Console.WriteLine(MyMethod(x => "Hi " + x));
public static string MyMethod(Func<string, string> strategy)
{
return strategy("Lijo").ToString();
}
参考文献
委托和接口如何可以互换使用?
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#是主流命令式语言中这一演变的先驱之一。
当我想使用另一个控件为某个控件的事件声明一个处理程序时,我发现它们很有用。 要做到这一点,你必须将控件的引用存储在类的字段中,这样你就可以在不同的方法中使用它们。
private ComboBox combo;
private Label label;
public CreateControls()
{
combo = new ComboBox();
label = new Label();
//some initializing code
combo.SelectedIndexChanged += new EventHandler(combo_SelectedIndexChanged);
}
void combo_SelectedIndexChanged(object sender, EventArgs e)
{
label.Text = combo.SelectedValue;
}
多亏了lambda表达式,你可以这样使用它:
public CreateControls()
{
ComboBox combo = new ComboBox();
Label label = new Label();
//some initializing code
combo.SelectedIndexChanged += (s, e) => {label.Text = combo.SelectedValue;};
}
容易得多。