关键字:delegate
定义:delegate void stopManchineryDelegate ();//类似方法的定义。
方法步骤:
进行委托(将三个类中的关闭方法委托给一个类,让委托类写一个方法,让委托类方法调用三个关闭方法):
(1)首先定义三个类,类中写方法。再定义一个控制类,用于写委托。
例:
class PaintingMachine
{
public void PaintOff()
{
Console.WriteLine("停止印刷~!");
}
}
class FoldingMachine
{
public void StopFolding()
{
Console.WriteLine("折叠机停止工作~!");
}
}
class WeldingManchine
{
public void FinishWelding()
{
Console.WriteLine("停止焊接工作~!");
}
}
再定义一个控制类,用于写委托。
class Controller
{
//待写;
}
(2)在控制类中,声明其他三个类类型的字段(就是三个类的对象实例名)。
例:
private FoldingMachine folder;
private WeldingManchine welder;
private PaintingMachine painter;
在控制类中,写入类类型字段的写入属性,以便于在主程序中将实例化对象赋值给控制类中的类类型的字段,使得类类型字段
拥有调用其类中方法权限。
例:
public FoldingMachine Folder
{
set { this.folder = value; }
}
public WeldingManchine Welder
{
set { this.welder = value; }
}
public PaintingMachine Painter
{
set { this.painter = value; }
}
(3)在主程序中,使用new关键字,对其他三个类进行实例化。
例:
FoldingMachine folder = new FoldingMachine();
WeldingManchine welder = new WeldingManchine();
PaintingMachine painter = new PaintingMachine();
(4)在控制类中写委托:
delegate void stopManchineryDelegat();//定义委托:stopManchineryDelegat
stopManchineryDelegat stopManchinery;//将委托具体化为:stopManchinery
(5)将委托写进委托类的一个方法中;
public void SetStopManchinery()
{
stopMnachinery +=floder.StopFolding;
stopMnachinery += painer.Paintoff;
stopMnachinery += .Paintoff;
}
在控制类中写一个shutup方法,调用SetStopManchinery()方法和委托;
例:
public void ShutDown()
{
SetStopManchinery();
stopManchinery();
}
(6)在主程序中实例化对象,用对象对其控制类中的类类型字段赋值,并且调用控制类中的ShutDown()方法。通过调用
ShutDown()方法,就可以明白委托的作用。
Controller controller = new Controller();
controller.Folder = folder;
controller.Welder = welder;
controller.Painter = painter;
controller.ShutDown();
总结:委托是一种数据类型,也可以说是是函数指针(方法与引用的结合。)