C#——《C#语言程序设计》实验报告——继承与多态——电视和电灯委托
生活随笔
收集整理的這篇文章主要介紹了
C#——《C#语言程序设计》实验报告——继承与多态——电视和电灯委托
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、實(shí)驗(yàn)?zāi)康?/h1>
二、實(shí)驗(yàn)內(nèi)容
有下面兩個類,代表電視和電燈,設(shè)計(jì)兩個委托,在Program類的Main函數(shù)中,同時打開電視和電燈,再同時關(guān)閉它們。
class TV{public void on(int channel){Console.WriteLine("電視已打開,在看" + channel + "頻道");}public void off(){Console.WriteLine("電視已關(guān)閉");}}class Lights{static bool[] light = new bool[5];public static void turnon(int no){if (no >= 1 && no <= 5){light[no - 1] = true;Console.WriteLine("已經(jīng)開了" + no + "號燈");}}public static void turnoff(){for (int i = 0; i < 5; i++)light[i] = false;Console.WriteLine("電燈已全部關(guān)閉");}}源代碼
using System;namespace Homework16 {class TV{public void on(int channel){Console.WriteLine("電視已打開,在看" + channel + "頻道");}public void off(){Console.WriteLine("電視已關(guān)閉");}}class Lights{static bool[] light = new bool[5];public static void turnon(int no){if (no >= 1 && no <= 5){light[no - 1] = true;Console.WriteLine("已經(jīng)開了" + no + "號燈");}}public static void turnoff(){for (int i = 0; i < 5; i++)light[i] = false;Console.WriteLine("電燈已全部關(guān)閉");}}public class Controller{//定義字段private TV tv;private Lights lights;//構(gòu)造函數(shù)public Controller() { }//定義委托類型startMachine ,返回值為Void。//所以要求委托指向的方法返回值也為空//delegate關(guān)鍵字相當(dāng)于類類型的class關(guān)鍵字public delegate void startMachine(int number);//聲明一個stopmMachine類型的對象public startMachine startmachine;//添加委托//定義委托類型stopMachine ,返回值為Void, stopMachine()的參數(shù)列表為空。//所以要求委托指向的方法返回值也為空,參數(shù)列表也為空。//delegate關(guān)鍵字相當(dāng)于類類型的class關(guān)鍵字public delegate void stopMachine();//聲明一個stopmMachine類型的對象public stopMachine stopmachine;//添加委托public void Add(startMachine startmethod,stopMachine stopmethod){ //實(shí)例化對象this.startmachine += startmethod;this.stopmachine += stopmethod;//相當(dāng)于//stopmachine = new stopMachine(tv.shutTV);//stopmachine = new stopMachine(computer.shutComputer);//stopmachine = new stopMachine(light.shutLight);}//刪除委托public void ReMove(startMachine startmethod,stopMachine stopmethod){this.stopmachine -= stopmethod;this.startmachine -= startmethod;}//調(diào)用委托public void open(int number){startmachine(number);}//調(diào)用委托public void shut(){stopmachine();}}class Program{static void Main(string[] args){//實(shí)例化類Controller controller = new Controller();TV tv = new TV();Lights light = new Lights();//添加委托controller.Add(tv.on,tv.off);controller.Add(Lights.turnon, Lights.turnoff);//調(diào)用委托Random random = new Random();controller.open(random.Next(1,5));controller.shut();Console.ReadKey();}} }運(yùn)行結(jié)果
三、實(shí)驗(yàn)心得與體會
參考文章
https://www.cnblogs.com/zcttxs/archive/2012/06/24/2560154.html
https://shentuzhigang.blog.csdn.net/article/details/105022881
https://www.cnblogs.com/Jeffrey-Chou/p/11907530.html
總結(jié)
以上是生活随笔為你收集整理的C#——《C#语言程序设计》实验报告——继承与多态——电视和电灯委托的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C#——《C#语言程序设计》实验报告——
- 下一篇: C#——《C#语言程序设计》实验报告——