using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 多态模拟移动硬盘和U盘 { class Program { static void Main(string[] args) { //用多态来实现U盘,Mp3,移动硬盘和电脑的对接,读取写入数据。 MobileTool mt = new UDisk(); Computer cpu = new Computer(); cpu.CpuRead(mt); cpu.CpuWrite(mt); Console.ReadKey(); } /// <summary> /// 抽象的父类 /// </summary> public abstract class MobileTool { public abstract void Read(); public abstract void Write(); } public class UDisk : MobileTool { public override void Read() { Console.WriteLine("U盘读取成功"); } public override void Write() { Console.WriteLine("U盘写入成功"); } } public class Mp3Disk : MobileTool { public override void Read() { Console.WriteLine("Mp3读取成功"); } public override void Write() { Console.WriteLine("Mp3写入成功"); } public void PlayMuisc() { Console.WriteLine("Mp3自己可以播放音乐"); } } public class MobileDisk : MobileTool { public override void Read() { Console.WriteLine("移动硬盘读取成功"); } public override void Write() { Console.WriteLine("移动硬盘写入成功"); } } public class Computer { public void CpuRead(MobileTool mt) { mt.Read(); } public void CpuWrite(MobileTool mt ) { mt.Read(); } } } }
在computer抓取父类的方法有多种:可以方法中传递参数抓取,可以通过构造函数,也可以通过属性来抓取。
static void Main(string[] args) { MobileTool mt = new UDisk(); Computer cpu = new Computer(); cpu.Mt = mt; cpu.CpuRead(); cpu.CpuWrite(); Console.ReadKey(); } public class Computer { private MobileTool _mt; internal MobileTool Mt { get { return _mt; } set { _mt = value; } } public void CpuRead() { Mt.Read(); } public void CpuWrite() { Mt.Read();
时间: 2024-10-09 19:53:19