委托 三步即可实现
2018-12-29 本文已影响0人
今天多云很多云
委托是C#里非常重要的应用。其实只要简单的三步就能用委托。编辑时间:20181229
- 声明委托
- 委托一样格式的方法
- 实例化委托
delegate int MyDelegete(int n);//一、声明委托
static int num = 10;
public static int Add(int n)//二、跟委托同样格式的方法
{
return num += n;
}
public static int Mul(int n)//二、跟委托同样格式的方法
{
return num *= n;
}
public static int GetNum()
{
return num;
}
private static void UseDelegateMethod(MyDelegete d)
{
d(10);
}
static void Main(string[] args)
{
MyDelegete d1 = new MyDelegete(Add);//三、声明委托
MyDelegete d2 = new MyDelegete(Mul);
d1(25); Console.WriteLine(GetNum());
d2(5); Console.WriteLine(GetNum());
MyDelegete d; d = d1;d += d2; //多播委托
d(10); Console.WriteLine(GetNum());
UseDelegateMethod(d1); Console.WriteLine(GetNum());//系数相同,用方法传委托对象
UseDelegateMethod(d2); Console.WriteLine(GetNum());
Console.ReadKey();
}
图片版本代码:
