C#委托的实例
//命名委托
//声明了一个委托,下一步需要实例化
public delegate void MyDelegate();
public class Person
{
public static void SayHello()
{
Console.WriteLine("Hello World");
//委托实例化
MyDelegate Dale = new MyDelegate(SayHello);
//调用
Dale();
}
}
多播委托
public delegate void MyDelegate();
public class Person
{
public static void SayHello()
{
MyDelegate MyDele = new MyDelegate(Order.BuyFood);
MyDele = MyDele + Order.BuyBeef;
MyDele += Order.BuyFish;
MyDele -= Order.BuyFood;
MyDele();
}
}
class Order
{
public static void BuyFish()
{
Console.WriteLine("你购买了一条鱼");
}
public static void BuyFood()
{
Console.WriteLine("你购买了食物");
}
public static void BuyCoco()
{
Console.WriteLine("你购买了奶茶");
}
public static void BuyBeef()
{
Console.WriteLine("你购买了牛肉");
}
}
————————————————————————————————————————————————————————————————————
匿名委托
public delegate void AreaDelegate(double length, double width);
Console.WriteLine("输入长度:");
double length = double.Parse(Console.ReadLine());
Console.WriteLine("输入宽度");
double width = double.Parse(Console.ReadLine());
//定义匿名委托
AreaDelegate area = delegate
{
double area = length * width;
Console.WriteLine(area);
};
//调用匿名委托
area(length, width);