/// <summary> /// 由于不知道到用户插入的是什么设备,所以使用抽象类 /// 含有每个设备都具备的读和写2个方法 /// </summary> public abstract class DiskFather { public abstract void Read(); public abstract void Write(); }
class MobileDisk : DiskFather { public override void Read() { Console.WriteLine("移动硬盘在读取数据"); } public override void Write() { Console.WriteLine("移动硬盘在写入数据"); } }
class UDisk : DiskFather { public override void Read() { Console.WriteLine("U盘在读取数据"); } public override void Write() { Console.WriteLine("U盘在写入数据"); } }
class MP3 : DiskFather { public void PlayMusic() { Console.WriteLine("MP3可以播放音乐"); } public override void Read() { Console.WriteLine("MP3在读取数据"); } public override void Write() { Console.WriteLine("MP3在写入数据"); } }
/// <summary> /// 电脑类 /// </summary> class Cpu { public DiskFather DF { get; set; } public void CpuRead() { this.DF.Read(); } public void CpuWrite() { this.DF.Write(); } }
static void Main(string[] args) { MobileDisk md = new MobileDisk(); MP3 mp3 = new MP3(); UDisk ud = new UDisk(); Cpu cpu = new Cpu(); //cpu.DF = md;//子类可以赋值给父类 //cpu.CpuRead(); //cpu.CpuWrite(); //cpu.DF = mp3; //cpu.CpuRead(); //cpu.CpuWrite(); cpu.DF = ud; cpu.CpuRead(); cpu.CpuWrite(); Console.ReadKey(); } }
时间: 2024-12-09 17:08:11