C#入门经典 第六章 委托
C#入门经典
第六章 6.6
委托的声明非常类似于函数,但不带函数体,且要使用delegate关键字。
委托的声明指定了一个返回类型和一个参数列表。
在定义了委托后,就可以声明该委托类型的变量。
接着把这个变量初始化为与委托有相同返回类型和参数列表的函数引用。
之后,就可以使用委托变量调用这个函数,就像该变量是一个函数一样。
有了引用函数的变量后,还可以执行不能用其它方式完成的操作。
例如,可以把委托变量作为参数传递给一个函数,这样,该函数就可以使用委托调用引用它的任何函数。
而且在运行之前无需知道调用的是那一个函数。
class Ch06Ex05 { //委托的声明非常类似于函数,但不带函数体,且要使用delegate关键字。 //委托的声明指定了一个返回类型和一个参数列表。 delegate double ProcessDelegate(double a,double b);//返回类型是double,参数列表:两个double变量a和b static double Multiply(double x,double y) { return x * y; } static double Divide(double m, double n) { return m / n; } public static void Method() { ProcessDelegate process;//在定义了委托后,就可以声明该委托类型的变量。 process = new ProcessDelegate(Multiply);//把委托变量初始化为与委托有相同返回类型和参数列表的函数引用。 Console.WriteLine("Multiply(100,10)={0}", process(100, 10));//使用委托变量调用这个函数,就像该变量是一个函数一样 process = new ProcessDelegate(Divide);//把委托变量初始化为与委托有相同返回类型和参数列表的函数引用。 process(100, 10);//使用委托变量调用这个函数,就像该变量是一个函数一样 Console.WriteLine("Divide(100,10)={0}", process(100, 10)); } } class Program { /// <summary> /// 主函数 /// </summary> /// <param name="args"></param> static void Main(string[] args) { Chapter06.Ch06Ex05.Method(); Console.Read(); } }
delegate关键字指定该定义是用于委托的,而不是用于函数的(该定义所在的位置与函数定义相同)
委托的三种用法
class Test { delegate void TestDelegate(string s); static void M(string s) { Console.WriteLine(s); } static void Main(string[] args) { // Original delegate syntax required // initialization with a named method. TestDelegate testDelA = new TestDelegate(M); // C# 2.0: A delegate can be initialized with // inline code, called an "anonymous method." This // method takes a string as an input parameter. TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); }; // C# 3.0. A delegate can be initialized with // a lambda expression. The lambda also takes a string // as an input parameter (x). The type of x is inferred by the compiler. TestDelegate testDelC = (x) => { Console.WriteLine(x); }; // Invoke the delegates. testDelA("Hello. My name is M and I write lines."); testDelB("That's nothing. I'm anonymous and "); testDelC("I'm a famous author."); // Keep console window open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } /* Output: Hello. My name is M and I write lines. That's nothing. I'm anonymous and I'm a famous author. Press any key to exit. */
ps:还有一种用法是,直接把方法名赋值给委托,不需要new
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了