C#中的委托

发布时间:2026/7/27 10:51:17
C#中的委托 C#中的委托本质上是一个装载函数与传递函数的容器可以作为类的成员也可以作为参数传递其可以起到存储函数使我们可以先执行其他逻辑再执行存储的函数的逻辑。using System; using System.Collections.Generic; namespace lesson11 { //1.委托的声明 delegate void MyFun();//用于装载无参无返回值的函数的委托容器 delegate int MyFun2(int a);//用于装载有一个int型参数返回int型变量的函数的委托容器 delegate T MyFun3T,K(T t,K k);//泛型委托 class Test { //2.委托作为类成员声明 public MyFun fun; public MyFun2 fun2; //3.委托作为函数参数使用 public void TestFun(MyFun fun, MyFun2 fun2) { //允许先执行其他逻辑再执行传入的函数 //...... int i 0; i; fun(); fun2(i); } //4.委托允许增加函数数量(一个委托可以装载多个函数即多播委托) public void AddFun(MyFun fun, MyFun2 fun2) { this.fun fun; this.fun2 fun2; } //5.委托允许减少函数数量 public void RemoveFun(MyFun fun, MyFun2 fun2) { this.fun - fun; this.fun2 - fun2; } } class Program { static void Main(string[] args) { //6.委托基本的函数装载与调用(装载与调用的两种方式本质上无区别) MyFun f new MyFun(Fun);//new装载 f.Invoke();//Inovke调用 MyFun f2 Fun;//赋值装载 f2();//函数式调用 MyFun2 f3 Fun2; Console.WriteLine(f3(5)); Console.WriteLine(***********************************); //7.作为类内成员与参数使用 Test t new Test(); t.TestFun(Fun, Fun2); Console.WriteLine(***********************************); //8.委托允许装载多个函数执行委托时按照装载的前后顺序执行 MyFun ff null; ff Fun; ff Fun3; ff(); Console.WriteLine(***********************************); //多函数装载被封装在类内的操作 t.AddFun(Fun, Fun2); t.fun(); t.fun2(50); Console.WriteLine(***********************************); //减少委托中的函数 ff - Fun3; ff(); ff - Fun3;//重复删除不存在的函数不会进行操作 ff null; if (ff ! null) { ff(); } Console.WriteLine(***********************************); //9.系统自定义好的委托类型 Action action Fun;//装载无参无返回函数的委托 action.Invoke(); Funcstring func Fun4;//装载允许自定义返回类型的无参函数的泛型委托 Console.WriteLine(func.Invoke()); Actionint,string action1 Fun5;//装载允许自定义参数类型与个数的无返回值的泛型委托(最多可传入的函数参数个数为16个) action1.Invoke(2,uuu); Funcint,int func1 Fun2;//装载允许自定义参数与返回值的类型与个数的泛型委托返回值作为最后一个泛型占位符传入 } static void Fun() { Console.WriteLine(aaa); } static void Fun3() { Console.WriteLine(bbb); } static int Fun2(int a) { return a; } static string Fun4() { return 泛型委托测试; } static void Fun5(int a, string b) { Console.WriteLine(${a} {b}); } } }