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

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

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

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


当前回答

Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:

using System;
using System.Linq;
using System.Linq.Expressions;


namespace ExpressionTreeThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
            var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
            Console.WriteLine(del(5)); //we are just invoking a delegate at this point
            Console.ReadKey();
        }
    }
}

This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.

其他回答

这样可以避免在远离使用方法的地方定义只在特定位置使用一次的方法。好的用途是作为泛型算法(如排序)的比较器,然后您可以定义一个自定义排序函数,在该函数中调用排序,而不是进一步迫使您查看其他地方以查看您正在排序的对象。

这并不是真正的创新。LISP拥有lambda函数已经有30年或更长时间了。

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清理了c# 2.0的匿名委托语法…例如

Strings.Find(s => s == "hello");

在c# 2.0中是这样完成的:

Strings.Find(delegate(String s) { return s == "hello"; });

在功能上,它们做的是完全相同的事情,只是语法更简洁。

在c#中,我们不能像在JavaScript中那样将函数作为参数传递。解决方法是使用委托。

当我们想参数化行为而不是值时,我们使用委托。Lambdas是编写委托的实用语法,可以很容易地将行为作为函数传递。