码迷,mamicode.com
首页 > 其他好文 > 详细

理解Lambda表达式和闭包

时间:2017-04-04 09:24:29      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:ring   nbsp   过程   是什么   指针   lap   表达   open   gif   

了解由函数指针到Lambda表达式的演化过程

技术分享

Lambda表达式的这种简洁的语法并不是什么古老的秘法,因为它并不难以理解(难以理解的代码只有一个目的,那就是吓唬程序员)

技术分享
 1 #include "stdafx.h"
 2 using namespace System;
 3 
 4 typedef void(*FunctionPointer)(System::String ^str);
 5 
 6 void HelloWorld(System::String ^str)
 7 {
 8     Console::WriteLine(str);
 9     Console::ReadLine();
10 }
11 
12 int main(array<System::String ^> ^args)
13 {
14     FunctionPointer fp = HelloWorld;
15     fp("Hello World");
16     return 0;
17 }
函数指针
技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace CharpFunctionPointer {
 6     class Program {
 7 
 8         delegate void FunctionPointer(string str);
 9 
10         static void Main(string[] args) {
11             FunctionPointer fp = HelloWorld;
12             fp("Hello World!");
13         }
14 
15         static void HelloWorld(string str) {
16             Console.WriteLine(str);
17             Console.ReadLine();
18         }
19     }
20 
21 }
委托
技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace CharpFunctionPointer {
 6     class Program {
 7 
 8         delegate void FunctionPointer(string str);
 9 
10         static void Main(string[] args) {
11             FunctionPointer fp = delegate (string s) {
12                 Console.WriteLine(s);
13                 Console.ReadLine();
14             };
15             fp("Hello World!");
16         }
17     }
18 
19 }
匿名委托
技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace CharpFunctionPointer {
 6     class Program {
 7 
 8         delegate void FunctionPointer(string str);
 9 
10         static void Main(string[] args) {
11             FunctionPointer fp =
12                 s => Console.WriteLine(s);
13 
14             fp("Hello World!");
15             Console.ReadLine();
16         }
17     }
18 }
Lambda表达式

技术分享

技术分享
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace CharpFunctionPointer {
 6     class Program {
 7 
 8         static void Main(string[] args) {
 9             Action<string> fp = s => Console.WriteLine(s);
10 
11             fp("Hello World!");
12             Console.ReadLine();
13         }
14     }
15 }
将Lambda表达式赋值给一个预定义的泛型委托

 

理解Lambda表达式和闭包

标签:ring   nbsp   过程   是什么   指针   lap   表达   open   gif   

原文地址:http://www.cnblogs.com/revoid/p/6664290.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!