不一样的风格,C#的lambda表达式
2016-10-20 22:22
260 查看
下面贴出代码
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<string, int> delegatetest1 = new Func<string, int>(callbackmethod); // //C#2.0中用匿名方法来创建委托实例,此事就不需要去额外定义回调方法callbackmethod了 Func<string, int> deledatetest2 = delegate(string text) { return text.Length; }; // //C# 3.0中使用lamabda表达式来创建委托实例 Func<string, int> delegatetest3 = (string text) => text.Length; // //可以省略类型参数string,从而代码再次简化 Func<string, int> delegatetest4 = (text) => text.Length; //括号省略 Func<string, int> 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()); } } }
相关文章推荐
- C# 3.0新特性体验之Lambda表达式_C#教程
- C# 3.0新特性体验之Lambda表达式
- Lambda 表达式(C# 编程指南)
- Lambda 表达式(C# 编程指南)
- Lambda 表达式(C# 编程指南)
- [MSDN]C# 3.0 锐利体验系列课程 之二 Lambda表达式
- 大马哈鱼的C#学习笔记(1):lambda表达式
- C# 委托的发展史: .Net 1.x 委托 =>.Net 2.x 匿名方法 => .Net 3.0/3.5 Lambda 表达式
- C# Lambda 表达式
- c# 3.0新特性之使用Lambda表达式
- Lambda 表达式(C# 编程指南)
- 从C# 3.0说以人为本(四)—— Lambda表达式
- 实例 C#3.0与C#2.0相比之新特性(四) Lambda 表达式
- Lambda 表达式(C# 编程指南)
- C# Lambda表达式事例
- C# 3.0新特性体验之Lambda表达式
- C#基础:Lambda表达式
- [原] C# 3.0的委托(delegate)及Lambda表达式应用实例
- C#教程:作为委托的Lambda表达式
- 软件开发与数学基础 一个C#中的例子——lambda表达式