每天学习一点.net(5) 利用匿名方法Lambda表达式(=>)实现委托

来源:互联网 发布:衣柜设计软件用哪款好 编辑:程序博客网 时间:2024/05/24 03:43

Lambda表达式的语法格式为: 参数列 => 语句或语句块

它是一个匿名函数。它包含表达式和语句,常用于创建委托或表达式目录树类型

通常Lambda表达式的参数都是可变类型的,由编译器自动确定它的具体类型。但有时编译器难于或无法推断输入类型,就需要为参数显示指定类型,既在参数之前添加参数类型。如下所示的Lambda表达式包括连个参数x和s。其中x是int类型,而s则是string类型。

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

当Lanbda表达式没有参数时,需要使用空的括号表示,如下所示。其中,“()”表示没有参数,而Amethod()是一个具体的方法,该方法的返回值就是Lambda表达式的结果。

() => AMethod()

 示例:

using System;using System.Threading;public static class CancellationDemo{    public static void Main()    {        CancellationTokenSource cs = new CancellationTokenSource();        ThreadPool.QueueUserWorkItem(o => Count(cs.Token, 1000));             Console.WriteLine("press <Enter> key to stop he child thread");        Console.ReadLine();        cs.Cancel();        Console.ReadLine();         }    private static void Count(CancellationToken token, int countTo)    {        for (int count = 0; count <= countTo; count++)        {            if (token.IsCancellationRequested)            {                Console.WriteLine("it is done by the main thread");                break;            }            Console.WriteLine(count);            Thread.Sleep(200);        }        Console.WriteLine("it is done");    }}

 ThreadPool.QueueUserWorkItem 是实现将一个异步的、计算限制的操作放到线程池的队列中。

ThreadPool.QueueUserWorkItem(Waitcallback Callback,Object state)
在ThreadPool.QueueUserWorkItem(o => Count(cs.Token, 1000)) 中,=>作为了一个匿名方法传递给QueueUserWorkItem
o为Object o,表示传入参数。

 


<script type="text/javascript"><!--google_ad_client = "ca-pub-1944176156128447";/* cnblogs 首页横幅 */google_ad_slot = "5419468456";google_ad_width = 728;google_ad_height = 90;//--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>