下面贴出代码

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;

namespace Lambda表达式

{

class Program

{

static void Main(string[] args)

{

//lambda表达式的演变过程

//下面是C#1.0中创建委托实例的代码

Func delegatetest1 = new Func(callbackmethod);

//

//C#2.0中用匿名方法来创建委托实例,此事就不需要去额外定义回调方法callbackmethod了

Func deledatetest2 = delegate(string text)

{

return text.Length;

};

//

//C# 3.0中使用lamabda表达式来创建委托实例

Func delegatetest3 = (string text) => text.Length;

//

//可以省略类型参数string,从而代码再次简化

Func delegatetest4 = (text) => text.Length;

//括号省略

Func delegatetest = text => text.Length;

//调用委托

Console.WriteLine("use lambda to retun text.length=" + delegatetest("helloworld"));

Console.WriteLine("------------------------------------------------------------");

//以上是lamada演变过程

//下面是lamada在订阅事件的使用

//定义一个按钮

Button btn = new Button() { Text = "点击我啊" };

btn.Click+=(sender,e)=>ReportEvent("点击按钮事件",sender,e);

//定义窗体显示

Form form = new Form() { Name = "在控制台创建的窗体", AutoSize = true, Controls = { btn } };

//运行窗体

Application.Run(form);

Console.Read();

}

private static int callbackmethod(string text)

{

return text.Length;

}

private static void ReportEvent(string title, object sender, EventArgs e)

{

Console.WriteLine("发生的事件为:{0}", title);

Console.WriteLine("发生事件的对象是:{0}",sender);

Console.WriteLine("发生事件的参数是:{0}",e.GetType());

}

}

}

 

查看原文