委托(delegate):可以理解为函数的一个包装,使C#当中的函数可以作为参数进行传递
- 委托是方法的抽象:它是存储一系列具有相同签名和返回类型的方法的地址,调用委托的时候,委托包装的方法将会被调用
- public delegate void MyDelegate(int a, string b);
- public void MyMethod(int aa,string bb){...}
- 委托链的添加/移除
namespace Demo8_4
{
class Program
{
public delegate string SayDel(string name);
public static string SayA(string name)
{
return name + "————哈哈哈";
}
public static string SayB(string name)
{
return name + "————hello";
}
public static void SayAB(SayDel say, string name)
{
Console.WriteLine(say.Invoke(name));//Invoke调用方法的意思
}
static void Main(string[] args)
{
SayAB(SayA,"你好");
SayAB(SayB,"hai");
B b = new B();
b.Action();
IPhone13ProMax i13 = new IPhone13ProMax();
i13.Action();
BB bb = new BB();
bb.Action();
bb.RemoDirnk();
bb.Action();
jisuan js;//声明委托变量
Math m = new Math();
js = new jisuan(m.add);
//js += m.jian;
int result = js(5, 3);
Console.WriteLine(result);
js += m.jian;
int result2 = js(5, 3);
Console.WriteLine(result2);
DOSomethings ds = new DOSomethings(new A1().BuySomething);
B1 b1 = new B1();
b1.Action(ds, "方便面");
C1 c1 = new C1();
c1.Action(ds, "火腿肠");
}
}
class A
{//A是被委托对象
public void Bufood()
{
Console.WriteLine("帮人买吃的");
}
}
class B
{//委托对象
public delegate void DoSomething();//声明了一个委托
DoSomething d = new DoSomething(new A().Bufood);//A是被委托对象
public void Action()
{
d();
}
}
class Foxconn
{
public void ProduceIPhone()
{
Console.WriteLine("我帮忙生产手机");
}
}
class IPhone13ProMax
{
public delegate void DoIPhone();
DoIPhone dp = new DoIPhone(new Foxconn().ProduceIPhone);
public void Action()
{
dp();//通过委托去调用方法
}
}
class AA
{
public void BuyFood(){Console.WriteLine("我帮忙买吃的");}
public void BuyDrink() { Console.WriteLine("我帮你买喝的"); }
}
class BB
{
public delegate void DoSomething();
private DoSomething ds;
AA aa = new AA();
public BB()
{
ds = aa.BuyFood;//赋值
ds += aa.BuyDrink;//绑定
//ds -= aa.BuyFood;//移除
}
public void Action()
{
ds();
}
public void RemoDirnk()
{
ds -= aa.BuyDrink;//移除
}
}
public delegate int jisuan(int num1, int num2);
class Math
{
public int add(int num1,int num2)
{
return num1 + num2;
}
public int jian(int num1,int num2)
{
return num1 - num2;
}
}
public delegate void DOSomethings(string name);
class A1
{
public void BuySomething(string name)
{
Console.WriteLine("我要帮忙买{0}", name);
}
}
class B1
{
public void Action(DOSomethings d1,string fbm)
{
d1(fbm);
}
}
class C1
{
public void Action(DOSomethings d2,string htc)
{
d2(htc);
}
}
}