了解由函数指针到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表达式赋值给一个预定义的泛型委托
时间: 2024-10-13 03:07:18