02、委托、lambda表达式、泛型委托、多播委托
1)为什么使用委托?
将一个方法作为参数传递给另一个方法。委托是一个数据类型,像类一样。故委托也是可以new的。
2)声明一个委托所指向的函数必须跟委托具有相同的参数和返回值。委托的声明跟类是同一个级别的。
1 //定义了一个无返回值,无参数的委托类型 2 public delegate void MyDelegate();
3)为什么要有匿名方法?
匿名方法一般只调用一次。而lambda表达式就是匿名方法的一个简化写法。
匿名方法不能直接在类中定义,而是在给委托变量赋值的时候,需要一个赋值方法,此时可以“现做现卖”。定义一个匿名方法传递给委托。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 MyDelegate m1 = delegate () 6 { 7 Console.WriteLine("我是一个无参,无返回值的匿名函数"); 8 }; 9 10 } 11 } 12 public delegate void MyDelegate();
4)lambda表达式的使用
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 MyDelegate m1 = () => 6 { 7 Console.WriteLine("我是一个无参,无返回值的lambda表达式"); 8 }; 9 10 } 11 } 12 public delegate void MyDelegate();
有参数无返回值的lambda的使用。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 MyDelegate m1 = m => 6 { 7 Console.WriteLine(m); 8 }; 9 m1("zhangsan");//输出zhangsan 10 11 } 12 } 13 public delegate void MyDelegate(string name);
有参数有返回值的lambda的使用。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 MyDelegate m1 = (a,b) => 6 { 7 Console.WriteLine(a+b); 8 return a + b; 9 }; 10 m1(1,2);//输出3 11 12 } 13 } 14 public delegate int MyDelegate(int a,int b);
5)泛型委托。系统给提供的委托类型,不需要在开发中再次定义。
Action泛型委托是没有返回值的,但是参数可以变化的。
Action的非泛型版本,就是一个无返回值。无参数的委托。
Func只有泛型版本,没有非泛型版本。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //Func委托最后一个类型是返回值类型,前面的都是参数类型 6 Func<int, int, int, int> FuncDelegate = (a, b, c) => 7 { 8 Console.WriteLine(a + b + c); 9 return a + b + c; 10 }; 11 12 } 13 }
6)多播委托。一个委托可以绑定多个方法。
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 //多播委托第一个赋值委托不能使用+=,必须使用= 6 Action<string> action = M1; 7 action += M2; 8 action += M3; 9 //如果想删除哪一种委托类型,就使用action -= M3; 10 } 11 static void M1(string name) 12 { 13 Console.WriteLine(name); 14 } 15 static void M2(string name) 16 { 17 Console.WriteLine(name); 18 } 19 static void M3(string name) 20 { 21 Console.WriteLine(name); 22 } 23 } 24 public delegate void MyDelegate(string name);
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!