c#基础知识篇-委托Func和Action区别
Func指向的方法必须有返回值。Action指向的方法必须无返回值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | static void TestA() { Console.WriteLine( "无参无返回值方法" ); Console.WriteLine( "TestA线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId); } static void TestB( int i, int j) { Console.WriteLine( "有参无返回值方法" ); Console.WriteLine( "TestB线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId); } static int TestC() { Thread.Sleep(1000); Console.WriteLine( "无参有返回值方法" ); Console.WriteLine( "TestC线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId); return 1; } static string TestD( int i, int j) { Thread.Sleep(2000); Console.WriteLine( "有参有返回值方法" ); Console.WriteLine( "TestD线程,当前线程ID:" + Thread.CurrentThread.ManagedThreadId); return (i + j).ToString(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | Action actionA = TestA; actionA.BeginInvoke( null , null ); Action< int , int > actionB = TestB; actionB.BeginInvoke(2, 3, null , null ); Func< int > funC = TestC; IAsyncResult resultC = funC.BeginInvoke( null , null ); while (!resultC.IsCompleted) { Console.WriteLine( "线程执行中,未结束" ); } int valueC = funC.EndInvoke(resultC); Console.WriteLine( "得到的值:" + valueC + ",当前线程ID:" + Thread.CurrentThread.ManagedThreadId + "" ); Func< int , int , string > funD = TestD; IAsyncResult resultD = funD.BeginInvoke(1, 2, null , null ); while (!resultD.IsCompleted) { Console.WriteLine( "线程执行中,未结束" ); } string valueD = funD.EndInvoke(resultD); Console.WriteLine( "得到的值:" + valueD + ",当前线程ID:" + Thread.CurrentThread.ManagedThreadId + "" ); Console.WriteLine( "主线程结束,当前主线程ID:" + Thread.CurrentThread.ManagedThreadId); |
人生如逆旅
我亦是行人
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律