Lambda表达式

1.  Lambda的Hello World

2.  Lambda表达式

3. Lambda代码块

4. 不确定参数的Lambda表达式

5. Lambda表达式中变量作用域

6. 参考资料

7. 代码下载 

1. Lambda的Hello World


 delegate int del(int i);

 // delegate hello world

del myDelegate = x => x * x;
int j = myDelegate(10);

上面代码首先声明一个代理del,然后在对del进行赋值是采用的是Lambda表达式的形式,通过赋值,del就能够表示输入x,返回x的平凡。

 

 

2.  Lambda表达式

简单的将Lambda就是在=>之后跟着的是一个表达式,上面的Hello World程序中就是Lambda表达式。另外的示例:

(int x, string s) => s.Length > x 

3. Lambda代码块


 TestTheSame testTheSame = 
                (x, y) => 
                {
                    return (x == y);
                };

 4. 不确定参数的Lambda表达式Func<T, TResult>

 通过使用Func<T, TResult>能够实现不确定参数的delegate,示例:


   delegate TResult Func<TArg, TResult>(TArg arg);

  Func<int, bool> myFunc1 =

                x => x == 5;
            Console.WriteLine(myFunc1(5));  // true
            // 这里是两个输入参数
            Func<int, int, int> myFunc2 = 
                (x, y) => x + y;
            Console.WriteLine(myFunc2(1, 2));   // 3

 5. Lambda表达式中变量作用域

 在Lambda表达式内部是能够改变全局变量的。msdn上的示例:


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

6. 参考资料

http://msdn.microsoft.com/en-us/library/bb397687.aspx

http://msdn.microsoft.com/en-us/library/orm-9780596516109-03-09.aspx

7. 代码下载

/Files/xuqiang/csharp/Program.rar 


posted @ 2011-01-28 19:55  qiang.xu  阅读(338)  评论(0)    收藏  举报