委托之Action与Func
1 例程代码:
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace 委托之Action与Func { class Program { static void Main( string [] args) { Console.WriteLine( "【1】演示Action 委托:" ); var actDele = new Action(TestMethods.SelfIntroduce); actDele += TestMethods.SayHi; actDele.Invoke(); //调用委托 ShowTool.PrintDelimiter(50); Console.WriteLine( "【2.1】演示Func<int,int,int>委托:" ); var func1 = new Func< int , int , int >(TestMethods.Add2Num); Console.WriteLine( "请输入第一个数:" ); int a = ShowTool.GetNumInit(); Console.WriteLine( "请输入第二个数:" ); int b = ShowTool.GetNumInit(); Console.WriteLine(func1.Invoke(a, b)); ShowTool.PrintDelimiter(50); Console.WriteLine( "【2.2】演示Func<double,double,double>委托:" ); var func2 = new Func< double , double , double >(TestMethods.Multiple2Num); Console.WriteLine( "请输入第一个数:" ); double x = ShowTool.GetNumDouble(); Console.WriteLine( "请输入第二个数:" ); double y = ShowTool.GetNumDouble(); Console.WriteLine(func2.Invoke(x, y)); Console.ReadKey(); } } class TestMethods { internal static void SayHi() { Console.WriteLine( "Hello,Dell Mao" ); } public static void SelfIntroduce() { Console.WriteLine( "Hi,My name is Dell Mao!" ); } public static int Add2Num( int a, int b) { return a + b; } public static double Multiple2Num( double a, double b) { return a * b; } } class ShowTool { public static void PrintDelimiter( int lenght) //打印一个分隔符 { if (lenght < 8) { lenght = 8; } for ( int i = 0; i < lenght; i++) { Console.Write( "=" ); } Console.WriteLine(); } public static int GetNumInit() { int a = 0; try { a = Convert.ToInt32(Console.ReadLine()); return a; } catch (Exception) { MessageBox.Show( "您输入的数据格式有误,将使用默认值0。" ); return a; } } public static double GetNumDouble() { double a = 0; try { a = Convert.ToDouble(Console.ReadLine()); return a; } catch (Exception) { MessageBox.Show( "您输入的数据格式有误,将使用默认值-999。" ); return a; } } } } |
2 运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App