码迷,mamicode.com
首页 > Web开发 > 详细

.Net学习笔记----2015-06-26(多态的练习)

时间:2015-06-27 01:16:20      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:

用多态模拟,将移动硬盘,U盘,MP3插到电脑上进行读写数据

技术分享

父类:用抽象类,因为不知道是什么样的移动设备插到电脑上,也不清楚怎样读写

    abstract class MobileStorage
    {
        public abstract void Read();
        public abstract void Write();
    }

移动硬盘类:

    class MobileDisk : MobileStorage
    {
        public override void Read()
        {
            Console.WriteLine("移动硬盘在读取数据");
        }

        public override void Write()
        {
            Console.WriteLine("移动硬盘在写入数据");
        }
    }

U盘类:

    class UDisk : MobileStorage
    {
        public override void Read()
        {
            Console.WriteLine("U盘在读取数据");
        }

        public override void Write()
        {
            Console.WriteLine("U盘在写入数据");
        }
    }

MP3类:

    class MP3 : MobileStorage
    {
        public override void Read()
        {
            Console.WriteLine("MP3在读取数据");
        }

        public override void Write()
        {
            Console.WriteLine("MP3在写入数据");
        }

        public void PlayMusic()
        {
            Console.WriteLine("MP3在播放音乐");
        }
    }

Computer类:

    class Computer
    {
        
        //通过定义字段获得父类
        private MobileStorage _ms;
        public MobileStorage Ms
        {
            get { return _ms; }
            set { _ms = value; }
        }

        public void CpuRead()
        {
            Ms.Read();
        }
        public void CpuWrite()
        {
            Ms.Write();
        }
        //通过传参获得父类
        //public void CpuRead(MobileStorage ms)
        //{
        //    ms.Read();
        //}

        //public void CpuWrite(MobileStorage ms)
        //{
        //    ms.Write();
        //}
    }

Main:

        static void Main(string[] args)
        {
            //用多态模拟,将移动硬盘,U盘,MP3插到电脑上进行读写数据
            //MobileDisk md = new MobileDisk();
            //UDisk u = new UDisk();
            //MP3 mp3 = new MP3();
            //Computer cpu = new Computer();
            //cpu.CpuRead(u);
            //cpu.CpuWrite(u);

            MobileStorage ms = new MobileDisk();//new UDisk();//new MP3(); 
            Computer cpu = new Computer();


            cpu.Ms = ms;
            cpu.CpuRead();
            cpu.CpuWrite();

            //cpu.CpuRead(ms);
            //cpu.CpuWrite(ms);
            Console.ReadKey();

        }

 

.Net学习笔记----2015-06-26(多态的练习)

标签:

原文地址:http://www.cnblogs.com/mikie/p/4603481.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!