Lambda学习

“Lambda 表达式”是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式目录树类型。

所有 Lambda 表达式都使用 Lambda 运算符 =>,该 Lambda 运算符的左边是输入参数(如果有),右边包含表达式或语句块

 

2.学习Lambda
 2.1 该 Lambda 运算符的左边是输入参数(如果有),右边包含表达式或语句块。
 2.2 只有在 Lambda 有一个输入参数时,括号才是可选的;否则括号是必需的。两个或更多输入参数由括在括号中的逗号分隔,
      例如: (x, y) => x == y
 2.3 参数类型: (int x, string s) => s.Length > x
 2.4 使用空括号指定零个输入参数: () => SomeMethod()
 2.5 Lambda 语句与 Lambda 表达式类似,只是语句括在大括号中:(input parameters) => {statement;}
 2.6 将Lambda表达式复制给委托,
      delegate void TestDelegate(string s); //定义委托
      TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };   //将红色的Lambda表达式复制给委托
      myDel("Hello");    //执行委托.
 2.7 带有标准查询运算符的 Lambda :
      public delegate TResult Func<TArg0, TResult>(TArg0 arg0)
      Func<int, bool> myFunc = x => x == 5;
      bool result = myFunc(4); // returns false of course

3.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 = 10return 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();
    }
}

 

 


 

三.总结委托用法
   1.正常使用:
     (1) 定义一个委托类型: public delegate void ShowValue();
     (2) 定义一个委托变量,并给委托变量赋值: ShowValue showMethod = testName.DisplayToWindow; 
     (3) 调用此委托,其实就是调用过程实体: showMethod
   2.匿名给委托赋值
     Action showMethod = delegate() { testName.DisplayToWindow();} ; 
     Action是系统定义的委托类型,"="右边是创建一个匿名方法.好处可以使用当前过程中的资源.例如:testName
     如果有参数,需要在delegate(参数1,参数2...)
   3.使用Lambda表达式为委托赋值
     Action showMethod = () => testName.DisplayToWindow();
四.线程.ThreadPool.QueueUserWorkItem 方法
   1.说明:将方法排入队列以便执行。此方法在有线程池线程变得可用时执行。
posted @ 2009-12-14 11:04  SouthAurora  Views(436)  Comments(0)    收藏  举报