一.委托的概念
using System;
//委托:delegate,函数指针
namespace _018_委托的概念
{
//声明委托
public delegate void MyDelegate();//像函数一样,可以写参数
//委托是和类平级的概念
//可以在类里也可以在类外
class Program
{
public static void FunctionTest()
{ }
static void Main(string[] args)
{
// MyDelegate myDelegate = new MyDelegate();//直接这样写会报错:不包含采用0个参数的构造函数
//实际上委托就是放函数的地方
//放除了delegate关键字之外,返回值,参数都一致的静态函数
MyDelegate myDelegate = new MyDelegate(FunctionTest);
}
}
}
二.委托的理解
using System;
namespace _019_委托的理解
{
public delegate int MyDelegate(int a);
public class DelegateClass
{
public static int a = 1;
public static int Add(int x)
{
a += x;
return a;
}
public static int Mult(int x)
{
a *= x;
return a;
}
public static int GetNum()
{
return a;
}
}
class Program
{
static void Main(string[] args)
{
//函数与委托绑定
MyDelegate myDelegate01 = new MyDelegate(DelegateClass.Add);
MyDelegate myDelegate02 = new MyDelegate(DelegateClass.Mult);
DelegateClass.a = 5;
int result = myDelegate01(1);
Console.WriteLine(result);
int multResult = myDelegate02(2);
Console.WriteLine(multResult);
}
}
}
三.多播委托
using System;
//多播委托:关联多个函数,但是会按照关联顺序依次执行
namespace _20_多播委托
{
public delegate int MyDelegate(int x);
public class DelegateClass
{
public static int number = 1;
public static int Add(int x)
{
number += x;
return number;
}
public static int Mult(int x)
{
number *= x;
return number;
}
public static int GetNum()
{
return number;
}
}
class Program
{
static void Main(string[] args)
{
MyDelegate myDelegate01 = null;
MyDelegate myDelegate02 = new MyDelegate(DelegateClass.Add);
MyDelegate myDelegate03 = new MyDelegate(DelegateClass.Mult);
myDelegate01 = myDelegate02;
myDelegate01 += myDelegate03;
int result = myDelegate01(1);
Console.WriteLine(result);
int multResult = myDelegate01(2);
Console.WriteLine(multResult);
}
}
}
四.多播委托实例
using System;
namespace _021_多播委托实例
{
public class A
{
public static void BuyFriut()
{
Console.WriteLine("请你帮我去买水果。");
}
public static void BuyBook()
{
Console.WriteLine("请你帮我买书");
}
}
class Program
{
public delegate void BuyThingEventHandler();
static void Main(string[] args)
{
BuyThingEventHandler buyThingEventHandler = new BuyThingEventHandler(A.BuyBook);
buyThingEventHandler += A.BuyFriut;
buyThingEventHandler();
}
}
}