C#委托中的匿名函数使用
首先,我们要看一下委托中使用匿名函数在C#中的发展史
1.委托的匿名方法使用的发展史
delegate void TestDel(string s);//定义一个委托
static void M(string s) //定义一个方法
{
Console.WriteLine(s);
}
TestDel test = new TestDel(M);//原始写法
//C# 2.0 匿名方法
TestDel t1 = delegate(string str) { Console.WriteLine(str); };
//C#3.0 Lambda 表达式
TestDel t2 = (x) => { Console.WriteLine(x); };
2.匿名方法在线程中的使用
/// <summary>
/// 匿名方法在线程中的使用
/// </summary>
private static void StartThread()
{
System.Threading.Thread th = new System.Threading.Thread(
delegate() {//匿名方法 参数列表 常用于事件中绑定的方法中 不能使用ref和out
Console.WriteLine(" Hello,");
Console.WriteLine(" world!");
}
);
th.Start();
}
3.委托在Lamda表达式中的应用
/// <summary>
/// Lamda表达式
/// </summary>
private static void Lamda()
{
//语法结构 ()=>expression
del myDel = (x,y) => x * y;
Console.WriteLine(myDel(9, 9));
Func<int, bool> myfun = x => x == 5;//定义一个lamda表达式
Console.WriteLine(myfun(4));
}
完整代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 匿名函数 8 { 9 class Program 10 { 11 delegate void TestDel(string s); 12 delegate int del(int i,int a); 13 delegate Tresult Func<Targ, Tresult>(Targ arg); 14 15 static void Main(string[] args) 16 { 17 TestDel test = new TestDel(M); 18 19 //匿名方法 20 //C# 2.0 21 TestDel t1 = delegate(string str) { Console.WriteLine(str); }; 22 23 //C#3.0 Lambda Expression 24 TestDel t2 = (x) => { Console.WriteLine(x); }; 25 26 test("这是基础的委托"); 27 t1("这是委托的匿名方法"); 28 t2("这是委托的Lamda表达式"); 29 30 StartThread(); 31 Lamda(); 32 Console.ReadLine(); 33 } 34 35 static void M(string s) 36 { 37 Console.WriteLine(s); 38 } 39 40 /// <summary> 41 /// 匿名方法在线程中的使用 42 /// </summary> 43 private static void StartThread() 44 { 45 System.Threading.Thread th = new System.Threading.Thread( 46 delegate() {//匿名方法 参数列表 常用于事件中绑定的方法中 不能使用ref和out 47 Console.WriteLine(" Hello,"); 48 Console.WriteLine(" world!"); 49 } 50 ); 51 th.Start(); 52 } 53 54 /// <summary> 55 /// Lamda表达式 56 /// </summary> 57 private static void Lamda() 58 { 59 //语法结构 ()=>expression 60 del myDel = (x,y) => x * y; 61 Console.WriteLine(myDel(9, 9)); 62 63 Func<int, bool> myfun = x => x == 5;//定义一个lamda表达式 64 Console.WriteLine(myfun(4)); 65 66 } 67 68 69 } 70 }

浙公网安备 33010602011771号