<1>为什么要有委托
-> 自定义执行
-> 实现回调
-> 实现多线程
<2>委托的使用
委托是一种类型
[访问修饰符] delegate 类型名 委托名(参数列表);
准备方法 -> 准备委托 -> 定义委托变量 -> 使用
(1)定义一个方法(静态)
static void Func()
{
}
(2)定义委托
public delegate void FuncDelegate();
(3)定义委托变量
FuncDelegate Wo;
(4)使用 使用类中的方法时
Wo = Func; 实例化类 BanZhang bz = new BanZhang();
Wo(); Wo = bz.Func;
Wo();
授权的方法:
// 1、直接等号
// 委托变量 = 方法名;
// 2、new一个委托对象
// 委托变量 = new 委托类型(方法名);
(4)委托变量的传值处理
public delegate void FuncDelegate(); //定义委托
public static void Func(FuncDelegate Func)
{
if (Func != null) //如果委托变量不为空,执行委托。
{
Func();
}
}
public static void Function()
{
Console.WriteLine("我被调用了. 哈哈哈. 终于出来了...");
}
static void Main(string[] args)
{
while (true)
{
FuncDelegate MyFunc = null; //定义委托变量MyFunc
Console.WriteLine("是否要调用方法(y...)");
if (Console.ReadLine() == "y")
{
MyFunc = Function; //使用委托
}
Func(MyFunc); //委托变量作为参数
Console.WriteLine();
Console.ReadKey();
} //这个例子说明了委托的自定义执行,即可以通过选择来决定方法的执行。
(5)委托的回调
委托的回调就是指在一个类中可以调用别的类的方法,或者两个类的方法进行互相调用。
(6)多线程
多线程就是指一个程序可以同时执行多个任务。
namespace _11多线程
{
class Program
{ //启用2个线程后,fun1和fun2同时执行。
static void Main(string[] args)
{
Thread t1 = new Thread(Func1); //创建线程
Thread t2 = new Thread(Func2);
t1.Start(); //开始线程
t2.Start();
}
static void Func1()
{
for (int i = 0; i < 100000000; i++)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(i);
Console.ForegroundColor = ConsoleColor.White;
}
}
static void Func2()
{
for (int i = 0; i < 100000000; i++)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(i);
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}
(7)委托链(多播委托)
-> 一个委托变量可以存放多个方法,就像一条锁链一样
-> 增加方法与减方法的方式
-> +=和-=
-> 调用委托就会依次执行该方法
-> 如果其中以个方法出现异常,那么就会停止所有方法
public delegate void FuncDelegate();
class Program
{
static void Main(string[] args)
{
FuncDelegate MyFunc;
MyFunc = Func1;
MyFunc += Func2;
MyFunc += Func3;
MyFunc += Func4; //假如这边不用+=而是用+的话,输出只有Func4的值,前面的值不会显示。
MyFunc();
Console.ReadKey();
}
public static void Func1()
{
Console.WriteLine("Func1");
}
public static void Func2()
{
Console.WriteLine("Func2");
}
public static void Func3()
{
Console.WriteLine("Func3");
}
public static void Func4()
{
Console.WriteLine("Func4");
}
}
-> 如果委托具有返回值,调用委托后,返回最后一个方法中的数据
-> 使用GetInvocationList()方法可以返回一个Delegate[]类型
-> Delegate类是一个抽象类,所有委托的父类
-> 委托链,必须保证类型一致
->委托链的使用类似于多态
委托链的一个应用模拟,见题目与代码。
(8)委托链的返回值
在委托变量上调用GetInvocationList方法,返回一个Delegate数组
Delegate[] ds = MyFunc.GetInvocationList();
for (int i = 0; i < ds.Length; i++)
{
int res = ((FuncDelegate)ds[i])(); //强转成自己定义的委托
Console.WriteLine(res);
}
(9)委托的本质
public delegate void FuncDelegate();
funcDelegat Func;
Func=Func1;
Func=Func2;
Delegate
-target Func2
MulticastDelegat
-invocationlist Func1 Func2 当执行+=在委托内部,有一个集合,存储方法
FuncDelegat
Invoke(); //执行委托时,先判断集合的元素,然后决定怎么执行。