目录
委托是什么
委托是 函数(方法)的容器
可以理解为表示函数(方法)的变量类型
用来 存储、传递函数(方法)
委托的本质是一个类,用来定义函数(方法)的类型(返回值和参数的类型)
不同的 函数(方法)必须对应和各自"格式"一致的委托
基本语法
关键字 : delegate
语法:访问修饰符 delegate 返回值 委托名(参数列表);
写在哪里?
可以申明在namespace和class语句块中
更多的写在namespace中
简单记忆委托语法 就是 函数申明语法前面加一个delegate关键字
定义自定义委托
访问修饰默认不写 为public 在别的命名空间中也能使用
private 其它命名空间就不能用了
一般使用public
申明了一个可以用来存储无参无返回值函数的容器
这里只是定义了规则 并没有使用
delegate void MyFun();
委托规则的申明 是不能重名(同一语句块中)
表示用来装载或传递 返回值为int 有一个int参数的函数的 委托 容器规则
public delegate int MyFun2(int a);
委托是支持 泛型的 可以让返回值和参数 可变 更方便我们的使用
delegate T MyFun3<T, K>(T v, K k);
委托常用在:
class Test
{
public MyFun fun;
public MyFun2 fun2;
public Action action;
public void TestFun( MyFun fun, MyFun2 fun2 )
{
//先处理一些别的逻辑 当这些逻辑处理完了 再执行传入的函数
int i = 1;
i *= 2;
i += 2;
//fun();
//fun2(i);
//this.fun = fun;
//this.fun2 = fun2;
}
增
public void AddFun(MyFun fun, MyFun2 fun2)
{
this.fun += fun;
this.fun2 += fun2;
}
#endregion
删
public void RemoveFun(MyFun fun, MyFun2 fun2)
{
//this.fun = this.fun - fun;
this.fun -= fun;
this.fun2 -= fun2;
}
系统定义好的委托
使用系统自带委托 需要引用using System;
无参无返回值
Action action = Fun;
action += Fun3;
action();
可以指定返回值类型的 泛型委托
Func<string> funcString = Fun4;
Func<int> funcInt = Fun5;
可以传n个参数的 系统提供了 1到16个参数的委托 直接用就行了
Action<int, string> action2 = Fun6;
可以穿n个参数的 并且有返回值的 系统也提供了 16个委托
Func<int, int> func2 = Fun2;
cs
class Mother
{
public void DoFood()
{
Console.WriteLine("妈妈做饭");
Console.WriteLine("妈妈饭做好了");
}
public void Eat()
{
Console.WriteLine("Mother吃饭");
}
}
class Father
{
public void Eat()
{
Console.WriteLine("Father吃饭");
}
}
class Son
{
public void Eat()
{
Console.WriteLine("Son吃饭");
}
}
class Program
{
public static void Main()
{
Action action=null;
Mother mother= new Mother();
Father father = new Father();
Son son = new Son();
action += mother.DoFood;
action += son.Eat;
action += mother.Eat;
action += father.Eat;
action();
}
}
cs
using System.Collections;
using System.Linq;
class Monster
{
public Action Action;
public void Dead()
{
if (Action != null)
{
Action();
}
Action = null;
}
}
class Player
{
public int money;
public void AddMoney()
{
money =money + 10;
}
}
class Scene
{
public void UpDate()
{
Console.WriteLine("界面数据刷新");
}
}
class Achievement
{
public int KillsNum;
public void AddKillsNum()
{
KillsNum++;
}
}
class Program
{
public static void Main()
{
Achievement achievement = new Achievement();
Monster monster = new Monster();
Player player = new Player();
Scene scene = new Scene();
monster.Action += achievement.AddKillsNum;
monster .Action += player.AddMoney;
monster.Action += scene.UpDate;
monster.Dead();
Console.WriteLine("玩家金币{0} 击杀数目前是{1} ", player.money, achievement.KillsNum);
}
}