一、實驗目的
- 掌握C#中各種成員的寫法;
- 掌握C#繼承和多態概念;
- 掌握常用接口的使用方法。
二、實驗內容
- 運用委託知識,完成以下程序:
有下面兩個類,代表電視和電燈,設計兩個委託,在Program類的Main函數中,同時打開電視和電燈,再同時關閉它們。
class TV
{
public void on(int channel)
{
Console.WriteLine("電視已打開,在看" + channel + "頻道");
}
public void off()
{
Console.WriteLine("電視已關閉");
}
}
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("已經開了" + no + "號燈");
}
}
public static void turnoff()
{
for (int i = 0; i < 5; i++)
light[i] = false;
Console.WriteLine("電燈已全部關閉");
}
}
源代碼
using System;
namespace Homework16
{
class TV
{
public void on(int channel)
{
Console.WriteLine("電視已打開,在看" + channel + "頻道");
}
public void off()
{
Console.WriteLine("電視已關閉");
}
}
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("已經開了" + no + "號燈");
}
}
public static void turnoff()
{
for (int i = 0; i < 5; i++)
light[i] = false;
Console.WriteLine("電燈已全部關閉");
}
}
public class Controller
{
//定義字段
private TV tv;
private Lights lights;
//構造函數
public Controller() { }
//定義委託類型startMachine ,返回值爲Void。
//所以要求委託指向的方法返回值也爲空
//delegate關鍵字相當於類類型的class關鍵字
public delegate void startMachine(int number);
//聲明一個stopmMachine類型的對象
public startMachine startmachine;
//添加委託
//定義委託類型stopMachine ,返回值爲Void, stopMachine()的參數列表爲空。
//所以要求委託指向的方法返回值也爲空,參數列表也爲空。
//delegate關鍵字相當於類類型的class關鍵字
public delegate void stopMachine();
//聲明一個stopmMachine類型的對象
public stopMachine stopmachine;
//添加委託
public void Add(startMachine startmethod,stopMachine stopmethod)
{ //實例化對象
this.startmachine += startmethod;
this.stopmachine += stopmethod;
//相當於
//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;
}
//調用委託
public void open(int number)
{
startmachine(number);
}
//調用委託
public void shut()
{
stopmachine();
}
}
class Program
{
static void Main(string[] args)
{
//實例化類
Controller controller = new Controller();
TV tv = new TV();
Lights light = new Lights();
//添加委託
controller.Add(tv.on,tv.off);
controller.Add(Lights.turnon, Lights.turnoff);
//調用委託
Random random = new Random();
controller.open(random.Next(1,5));
controller.shut();
Console.ReadKey();
}
}
}
運行結果
三、實驗心得與體會
- 掌握C#中各種成員的寫法;
- 掌握C#繼承和多態概念;
- 掌握常用接口的使用方法。
參考文章
https://www.cnblogs.com/zcttxs/archive/2012/06/24/2560154.html
https://shentuzhigang.blog.csdn.net/article/details/105022881