定义:委托是引用类型,将方法作为参数传递到另一个方法
声明:delegate 返回类型 委托名(参数)
例:
1.委托
//声明委托,返回类型为int,并且有两个参数
public delegate int GetSum(int a, int b);
public static int Sum(int a,int b)
{
return a + b;
}
static void Main(string[] args)
{
GetSum getSum = Sum; //将方法Sum传递到委托GetSum
//GetSum getSum = delegate (int a, int b) { return a + b; }; //匿名委托
//GetSum getSum = (int a, int b) => { return a + b; }; //lambda表达式
Console.WriteLine(getSum(1, 2));
}
2.C#已声明好的委托,System.Func和System.Action,其中func为有返回值,Action为无返回值
static void Main(string[] args)
{
Func<int, int, int> func = Sum; //指向有返回值的方法
Console.WriteLine(func(1, 2));
Action<int> action = Test; //指向无返回值的方法
action(1);
}
public static void Test(int a)
{
Console.WriteLine(a);
}
3.多播委托
定义:在一个委托中注册多个方法,用加减号实现添加或撤销
public delegate void Buy(); //声明购物委托
public static void BuyWater()
{
Console.WriteLine("水");
}
public static void BuyFruits()
{
Console.WriteLine("水果");
}
public static void BuyVegetable()
{
Console.WriteLine("蔬菜");
}
static void Main(string[] args)
{
Buy buy = BuyWater; //买水
buy += BuyFruits; //买买水果
buy += BuyVegetable; //买蔬菜
buy -= BuyWater; //撤销买水
buy();
Console.ReadKey();
}