我已经快速阅读了Microsoft Lambda表达式文档。

不过,这样的例子帮助我更好地理解:

delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

不过,我还是不明白为什么这是一种创新。它只是一个在“方法变量”结束时死亡的方法,对吧?为什么我要用这个而不是真正的方法?


当前回答

这是一种将小操作放在非常接近使用位置的地方的方法(与在接近使用点的地方声明变量没有什么不同)。这将使您的代码更具可读性。通过匿名化表达式,如果在其他地方使用了该函数并对其进行了修改以“增强”它,那么其他人就很难破坏您的客户端代码。

同样,为什么需要使用foreach?你可以用一个简单的for循环来完成foreach中的所有事情,或者直接使用IEnumerable。答案:你不需要它,但它使你的代码更可读。

其他回答

您还可以在编写作用于方法的泛型代码时使用lambda表达式。

例如:计算方法调用所花费的时间的泛型函数。(即这里的动作)

public static long Measure(Action action)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    action();
    sw.Stop();
    return sw.ElapsedMilliseconds;
}

你可以使用lambda表达式调用上述方法,如下所示,

var timeTaken = Measure(() => yourMethod(param));

表达式允许您从方法和out参数中获取返回值

var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));

Lambda表达式是表示匿名方法的一种简洁方式。匿名方法和Lambda表达式都允许您内联定义方法实现,但是,匿名方法显式地要求您定义方法的参数类型和返回类型。Lambda表达式使用c# 3.0的类型推断特性,该特性允许编译器根据上下文推断变量的类型。这是非常方便的,因为这节省了我们大量的输入!

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表达式就像代替委托实例编写的匿名方法。

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();
    }

参考文献

委托和接口如何可以互换使用?

这是一种将小操作放在非常接近使用位置的地方的方法(与在接近使用点的地方声明变量没有什么不同)。这将使您的代码更具可读性。通过匿名化表达式,如果在其他地方使用了该函数并对其进行了修改以“增强”它,那么其他人就很难破坏您的客户端代码。

同样,为什么需要使用foreach?你可以用一个简单的for循环来完成foreach中的所有事情,或者直接使用IEnumerable。答案:你不需要它,但它使你的代码更可读。