回顾C#3.0新特性(3)

四 Lambda表达式

MSDN中的描述:

在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式。

使用最多的地方还是在LINQ。表现为  “=>” 符号,念 goes to.

同一种函数两种表达方式来描述什么叫Lambda

Lambda表达式

var results = people.Where(p=>p.LastName == "White");

匿名函数来实现

var results1 = people.Where(
    delegate(Person p)
        {
            return p.LastName == "white";
        }
    );

 

表现形式为:

(input parameters) => expression
(x, y) => x == y
(int x, string s) => s.Length > x
() => SomeMethod()

左边为参数,如果没有留空。可以写入参数类型。

右边可以用花括号括起来,如果内容比较多的话。这样的话就叫Lambda语句。注意语句数量不应该太多。

 

Lambda 表达式中的变量范围

先意会观察一下Lambda使用“外部变量”

delegate bool D();
    delegate bool D2(int i);
 
    class Test
    {
        D del;
        D2 del2;
        public void TestMethod(int input)
        {
            int j = 0;
            // Initialize the delegates with lambda expressions.
            // Note access to 2 outer variables.
            // del will be invoked within this method.
            del = () => { j = 10;  return j > input; };
 
            // del2 will be invoked after TestMethod goes out of scope.
            del2 = (x) => {return x == j; };
            
            // Demonstrate value of j:
            // Output: j = 0 
            // The delegate has not been invoked yet.
            Console.WriteLine("j = {0}", j);
 
            // Invoke the delegate.
            bool boolResult = del();
 
            // Output: j = 10 b = True
            Console.WriteLine("j = {0}. b = {1}", j, boolResult);
        }
 
        static void Main()
        {
            Test test = new Test();
            test.TestMethod(5);
 
            // Prove that del2 still has a copy of
            // local variable j from TestMethod.
            bool result = test.del2(10);
 
            // Output: True
            Console.WriteLine(result);
            
            Console.ReadKey();
        }
    }
 

存储通过这种方法捕获的变量以供在 Lambda 表达式中使用,即使变量将以其他方式超出范围或被作为垃圾回收。

这句话需要在实践中体会一下

 

五 查询关键字

这方面其实就是LINQ了,观察一个表达式理解一下:

class LINQQueryExpressions
{
    static void Main()
    {
 
        // Specify the data source.
        int[] scores = new int[] { 97, 92, 81, 60 };
 
        // Define the query expression.
        IEnumerable<int> scoreQuery =
            from score in scores
            where score > 80
            select score;
 
        // Execute the query.
        foreach (int i in scoreQuery)
        {
            Console.Write(i + " ");
        }            
    }
}
// Output: 97 92 81

只要是实现了IEnumerable接口的都可以以这种方式搜索结果。

这里点到为止,具体深入讨论将会再开启一个系列。

posted @ 2009-03-10 08:44  my36z  阅读(261)  评论(0编辑  收藏  举报