Files
2025-10-17 10:27:36 +08:00

179 lines
4.9 KiB
C#

namespace Lesson12_委托
{
#region 知识点一 委托是什么
//委托是函数的容器
//可以理解为表示函数(方法)的变量类型
//用来 存储、传递函数
//委托的本质是一个类,用来定义函数(方法)的类型(返回值和参数的类型)
//不同的 函数必须对应和自己格式一致的委托
#endregion
#region 知识点二 基本语法
//关键字:delegate
//语法:访问修饰符 delegate 返回值 委托名(参数列表);
//写在哪里?
//可以在namespace的class语句种
//更多写在namespace种
//简单记忆委托语法就是 函数声明语法前加一个delegate关键字
#endregion
#region 知识点三 定义自定义委托
//访问修饰符不写 默认为public在别的命名空间中也能使用
//private其他命名空间就用不了了
//但一般使用public
delegate void MyFun();
delegate int MyFun2(int a);
#endregion
#region 知识点四 使用定义好的委托
//委托变量是函数的容器
//委托常用在:
//1.作为类的成员
//2.作为函数的参数
class Test
{
public MyFun fun;
public MyFun2 fun2;
public void TestFun(MyFun f, MyFun2 f2)
{
//一般是先处理一些别的逻辑 当这些逻辑处理完毕后 再调用传递进来的函数
f();
Console.WriteLine(f2(123));
this.fun = f;
this.fun2 = f2;
}
public void AddFun(MyFun fun,MyFun2 fun2)
{
this.fun += fun;
this.fun2 += fun2;
}
public void RemoveFun(MyFun fun, MyFun2 fun2)
{
this.fun -= fun;
this.fun2 -= fun2;
}
}
#endregion
#region 知识点五 委托变量可以存储多个函数
//上方的例子已经演示
#endregion
class Program
{
static void Main(string[] args)
{
Console.WriteLine("委托");
MyFun f = new MyFun(Fun);
Console.WriteLine("别的逻辑操作");
f.Invoke();//调用委托变量存储的函数
MyFun f2 = Fun;//简写
Console.WriteLine("别的逻辑操作");
f2();
//MyFun f2 = Fun2;//格式错误 不同格式的函数不能存储到同一个委托变量中
MyFun2 f21 = Fun2;
Console.WriteLine(f21(123));
MyFun2 f22 = new MyFun2(Fun2);
Console.WriteLine(f22.Invoke(123));
Test t = new Test();
t.TestFun(Fun, Fun2);
Console.WriteLine("____________________");
//如何用委托存储多个函数
MyFun ff = Fun;
ff += Fun3;//多加了Fun3,所以会调用两个函数
ff();
//完全写法是
ff = ff + Fun;
Console.WriteLine("____________________");
t.AddFun(Fun, Fun2);
t.fun();
t.fun2(123);
Console.WriteLine("____________________");
ff = null;
ff += Fun;
ff += Fun3;
ff();
Console.WriteLine("执行删除后:");
ff -= Fun;
ff();
ff -= Fun;//多删不会报错但也无效
#region 知识点六 系统定义好的委托
Console.WriteLine("____________________");
//Action 没有返回值的委托,需要引用的命名空间 System
Action a = Fun;
//之前的操作也可以用
a += Fun3;
a();
Console.WriteLine("____________________");
//Func<> 有返回值的委托,最后一个类型参数是返回值类型,前面的类型参数是参数类型
Func<string> funcString = Fun4;
//Func<int> funcInt = xxxx;
//可以传n个参数的 系统提供了 1到16个参数的Func<> 直接使用
Action<int, string> a2 = Fun6;
//Action用来存储没有返回值的函数
//Func用来存储有返回值的函数
//两个委托都可以以泛型方式同时存储多个函数
#endregion
}
static void Fun()
{
Console.WriteLine("这是Fun()函数");
}
static void Fun3()
{
Console.WriteLine("这是Fun3()函数");
}
static string Fun4()
{
return "";
}
static void Fun6(int i,string s)
{
}
static int Fun2(int a)
{
return a;
}
}
}
//总结
//委托是函数的容器
//可以用 委托变量 来存储、传递函数
//系统提供了 Action 和 Func 两个通用委托
//Action:没有返回值 参数数量0~16个
//Func:有返回值 参数数量0~16个(最后一个类型参数是返回值类型)