C#系列-多态

00解释

1、绝对路径和相对路径
绝对路径:通过给定的这个路径直接能在我的电脑中找到这个文件。
相对路径:文件相对于应用程序的路径。
结论:
我们在开发中应该去尽量的使用相对路径。
2、装箱、拆箱
装箱:就是将值类型转换为引用类型。
拆箱:将引用类型转换为值类型。
看两种类型是否发生了装箱或者拆箱,要看,这两种类型是否存在继承关系。
3、将创建文件流对象的过程写在using当中,会自动的帮助我们释放流所占用的资源。

4、实现多态的手段
1)、虚方法
步骤:
1、将父类的方法标记为虚方法 ,使用关键字 virtual,这个函数可以被子类重新写一个遍。
2)、抽象类
当父类中的方法不知道如何去实现的时候,可以考虑将父类写成抽象类,将方法写成抽象方法。

1、List泛型集合

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _02_List泛型集合
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建泛型集合对象
            //List<int> list = new List<int>();
            //list.Add(1);
            //list.Add(2);
            //list.Add(3);

            //list.AddRange(new int[] { 1, 2, 3, 4, 5, 6 });
            //list.AddRange(list);

            //List泛型集合可以转换为数组
            //int[] nums = list.ToArray();

            //List<string> listStr = new List<string>();

            //string[] str = listStr.ToArray();


            //char[] chs = new char[] { 'c', 'b', 'a' };
            //List<char> listChar = chs.ToList();
            //for (int i = 0; i < listChar.Count; i++)
            //{
            //    Console.WriteLine(listChar[i]);
            //}

               List<int> listTwo = nums.ToList();


            //for (int i = 0; i < list.Count; i++)
            //{
            //    Console.WriteLine(list[i]);
            //}
            Console.ReadKey();
        }
    }
}

2、装箱和拆箱

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03_装箱和拆箱
{
    class Program
    {
        static void Main(string[] args)
        {
            //int n = 10;
            //object o = n;//装箱
            //int nn = (int)o;//拆箱


            //ArrayList list = new ArrayList();
            //List<int> list = new List<int>();
            这个循环发生了100万次装箱操作
            //Stopwatch sw = new Stopwatch();
            00:00:02.4370587
            00:00:00.2857600
            //sw.Start();
            //for (int i = 0; i < 10000000; i++)
            //{
            //    list.Add(i);
            //}
            //sw.Stop();
            //Console.WriteLine(sw.Elapsed);
            //Console.ReadKey();


            //这个地方没有发生任意类型的装箱或者拆箱
            //string str = "123";
            //int n = Convert.ToInt32(str);


            int n = 10;
            IComparable i = n;//装箱

            //发生
        }
    }
}

3、Dictionary

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04Dictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "张三");
            dic.Add(2, "李四");
            dic.Add(3, "王五");
            dic[1] = "新来的";
            foreach (KeyValuePair<int,string> kv in dic)
            {
                Console.WriteLine("{0}---{1}",kv.Key,kv.Value);
            }

            //foreach (var item in dic.Keys)
            //{
            //    Console.WriteLine("{0}---{1}",item,dic[item]);
            //}
            Console.ReadKey();
        }
    }
}

4、泛型集合的练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05泛型集合的练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //将一个数组中的奇数放到一个集合中,再将偶数放到另一个集合中
            //最终将两个集合合并为一个集合,并且奇数显示在左边 偶数显示在右边。

            //int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            //List<int> listOu = new List<int>();
            //List<int> listJi = new List<int>();
            //for (int i = 0; i < nums.Length; i++)
            //{
            //    if (nums[i] % 2 == 0)
            //    {
            //        listOu.Add(nums[i]);
            //    }
            //    else
            //    {
            //        listJi.Add(nums[i]);
            //    }
            //}


            listOu.AddRange(listJi);
            foreach (int item in listOu)
            {
                Console.Write(item+"  ");
            }


            //listJi.AddRange(listOu);
            //foreach (int item in listJi)
            //{
            //    Console.Write(item+"  ");
            //}
            //Console.ReadKey();
            List<int> listSum = new List<int>();
            listSum.AddRange(listOu);
            listSum.AddRange(listJi);

            //提手用户输入一个字符串,通过foreach循环将用户输入的字符串赋值给一个字符数组

            //Console.WriteLine("请输入一个字符串");
            //string input = Console.ReadLine();
            //char[] chs = new char[input.Length];
            //int i = 0;
            //foreach (var item in input)
            //{
            //    chs[i] = item;
            //    i++;
            //}

            //foreach (var item in chs)
            //{
            //    Console.WriteLine(item);
            //}
            //Console.ReadKey();

            //统计 Welcome to china中每个字符出现的次数 不考虑大小写

            string str = "Welcome to China";
            //字符 ------->出现的次数
            //键---------->值
            Dictionary<char, int> dic = new Dictionary<char, int>();
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i] == ' ')
                {
                    continue;
                }
                //如果dic已经包含了当前循环到的这个键 
                if (dic.ContainsKey(str[i]))
                {
                    //值再次加1
                    dic[str[i]]++;
                }
                else//这个字符在集合当中是第一次出现
                {
                    dic[str[i]] = 1;
                }
            }

            foreach (KeyValuePair<char,int> kv in dic)
            {
                Console.WriteLine("字母{0}出现了{1}次",kv.Key,kv.Value);
            }
            Console.ReadKey();

            //w  1


        }
    }
}

5、文件流

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _06文件流
{
    class Program
    {
        static void Main(string[] args)
        {

            //使用FileStream来读取数据
            FileStream fsRead = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Read);
            byte[] buffer = new byte[1024 * 1024 * 5];
            //3.8M  5M
            //返回本次实际读取到的有效字节数
            int r = fsRead.Read(buffer, 0, buffer.Length);
            //将字节数组中每一个元素按照指定的编码格式解码成字符串
            string s = Encoding.UTF8.GetString(buffer, 0, r);
            //关闭流
            fsRead.Close();
            //释放流所占用的资源
            fsRead.Dispose();
            Console.WriteLine(s);
            Console.ReadKey();



            //使用FileStream来写入数据
            //using (FileStream fsWrite = new FileStream(@"C:\Users\SpringRain\Desktop\new.txt", FileMode.OpenOrCreate, FileAccess.Write))
            //{
            //    string str = "看我游牧又把你覆盖掉";
            //    byte[] buffer = Encoding.UTF8.GetBytes(str);
            //    fsWrite.Write(buffer, 0, buffer.Length);
            //}
            //Console.WriteLine("写入OK");
            //Console.ReadKey();
        }
    }
}

6、使用文件流来实现多媒体文件的复制

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _07使用文件流来实现多媒体文件的复制
{
    class Program
    {
        static void Main(string[] args)
        {
            //思路:就是先将要复制的多媒体文件读取出来,然后再写入到你指定的位置
            string source = @"C:\Users\SpringRain\Desktop\1、复习.wmv";
            string target = @"C:\Users\SpringRain\Desktop\new.wmv";
            CopyFile(source, target);
            Console.WriteLine("复制成功");
            Console.ReadKey();
        }

        public static void CopyFile(string soucre, string target)
        {
            //1、我们创建一个负责读取的流
            using (FileStream fsRead = new FileStream(soucre, FileMode.Open, FileAccess.Read))
            {
                //2、创建一个负责写入的流
                using (FileStream fsWrite = new FileStream(target, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    byte[] buffer = new byte[1024 * 1024 * 5];
                    //因为文件可能会比较大,所以我们在读取的时候 应该通过一个循环去读取
                    while (true)
                    {
                        //返回本次读取实际读取到的字节数
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        //如果返回一个0,也就意味什么都没有读取到,读取完了
                        if (r == 0)
                        {
                            break;
                        }
                        fsWrite.Write(buffer, 0, r);
                    }

                 
                }
            }
        }


    }
}

7、StreamReader和StreamWriter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace _08StreamReader和StreamWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用StreamReader来读取一个文本文件
            //using (StreamReader sr = new StreamReader(@"C:\Users\SpringRain\Desktop\抽象类特点.txt",Encoding.Default))
            //{
            //    while (!sr.EndOfStream)
            //    {
            //        Console.WriteLine(sr.ReadLine());
            //    }
            //}


            //使用StreamWriter来写入一个文本文件
            using (StreamWriter sw = new StreamWriter(@"C:\Users\SpringRain\Desktop\newnew.txt",true))
            {
                sw.Write("看我有木有把你覆盖掉");
            }
            Console.WriteLine("OK");
            Console.ReadKey();
        }
    }
}

8、多态

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09多态
{
    class Program
    {
        static void Main(string[] args)
        {
            //概念:让一个对象能够表现出多种的状态(类型)
            //实现多态的3种手段:1、虚方法 2、抽象类 3、接口

            Chinese cn1 = new Chinese("韩梅梅");
            Chinese cn2 = new Chinese("李雷");
            Japanese j1 = new Japanese("树下君");
            Japanese j2 = new Japanese("井边子");
            Korea k1 = new Korea("金秀贤");
            Korea k2 = new Korea("金贤秀");
            American a1 = new American("科比布莱恩特");
            American a2 = new American("奥尼尔");
            Person[] pers = { cn1, cn2, j1, j2, k1, k2, a1, a2, new English("格林"), new English("玛利亚") };

            for (int i = 0; i < pers.Length; i++)
            {
                //if (pers[i] is Chinese)
                //{
                //    ((Chinese)pers[i]).SayHello();
                //}
                //else if (pers[i] is Japanese)
                //{
                //    ((Japanese)pers[i]).SayHello();
                //}
                //else if (pers[i] is Korea)
                //{
                //    ((Korea)pers[i]).SayHello();
                //}
                //else
                //{
                //    ((American)pers[i]).SayHello();
                //}


                pers[i].SayHello();
            }
            Console.ReadKey();
        }
    }

    public class Person
    {
        private string _name;
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public Person(string name)
        {
            this.Name = name;
        }
        public virtual void SayHello()
        {
            Console.WriteLine("我是人类");
        }

    }

    public class Chinese : Person
    {
        public Chinese(string name)
            : base(name)
        {

        }

        public override void SayHello()
        {
            Console.WriteLine("我是中国人,我叫{0}", this.Name);
        }
    }
    public class Japanese : Person
    {
        public Japanese(string name)
            : base(name)
        { }

        public override void SayHello()
        {
            Console.WriteLine("我是脚盆国人,我叫{0}", this.Name);
        }
    }
    public class Korea : Person
    {
        public Korea(string name)
            : base(name)
        {

        }


        public override void SayHello()
        {
            Console.WriteLine("我是棒之思密达,我叫{0}", this.Name);
        }
    }
    public class American : Person
    {
        public American(string name)
            : base(name)
        {

        }

        public override void SayHello()
        {
            Console.WriteLine("我叫{0},我是米国人", this.Name);
        }
    }


    public class English : Person
    {
        public English(string name)
            : base(name)
        { }

        public override void SayHello()
        {
            Console.WriteLine("我是英国人");
        }
    }

}

9、多态练习

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _10多态练习
{
    class Program
    {
        static void Main(string[] args)
        {
            //真的鸭子嘎嘎叫 木头鸭子吱吱叫 橡皮鸭子唧唧叫
            //RealDuck rd = new RealDuck();
            //rd.Bark();
            //MuDuck md = new MuDuck();
            //md.Bark();
            //XPDuck xd = new XPDuck();
            //xd.Bark();
            //Console.ReadKey();

            //RealDuck rd = new RealDuck();
            //MuDuck md = new MuDuck();
            //XPDuck xd = new XPDuck();
            //RealDuck[] ducks = { rd, md, xd };
            //for (int i = 0; i < ducks.Length; i++)
            //{
            //    ducks[i].Bark();
            //}
            //Console.ReadKey();


            //经理十一点打卡 员工9点打卡 程序猿不打卡
            //Employee emp = new Employee();
            //Manager mg = new Manager();
            //Programmer pm = new Programmer();
            //Employee[] emps = { emp, mg, pm };
            //for (int i = 0; i < emps.Length; i++)
            //{
            //    emps[i].DaKa();
            //}
            //Console.ReadKey();



            //狗狗会叫 猫咪也会叫

        }
    }

    public class Animal
    {
        public void Bark()
        { 
            
        }
    }


    public class Employee
    {
        public virtual void DaKa()
        {
            Console.WriteLine("九点打卡");
        }
    }

    public class Manager : Employee
    {
        public override void DaKa()
        {
            Console.WriteLine("经理11点打卡");
        }
    }

    public class Programmer : Employee
    {
        public override void DaKa()
        {
            Console.WriteLine("程序猿不打卡");
        }
    }





    public class RealDuck
    {
        public virtual void Bark()
        {
            Console.WriteLine("真的鸭子嘎嘎叫");
        }
    }

    public class MuDuck : RealDuck
    {
        public override void Bark()
        {
            Console.WriteLine("木头鸭子吱吱叫");
        }
    }

    public class XPDuck : RealDuck
    {
        public override void Bark()
        {
            Console.WriteLine("橡皮鸭子唧唧叫");
        }
    }
}

10、抽象类一

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _11_抽象类
{
    class Program
    {
        static void Main(string[] args)
        {
            //狗狗会叫 猫咪会叫

            Animal a = new Cat();//new Dog();
            a.Bark();
            
            Console.ReadKey();
        }
    }

    public abstract class Animal
    {

        public virtual void T()
        {
            Console.WriteLine("动物有声明");
        }

        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        public Animal(int age)
        {
            this.Age = age;
        }
        public abstract void Bark();
        public abstract string Name
        {
            get;
            set;
        }

     //   public abstract string TestString(string name);


        public Animal()
        { 
            
        }
        //public void Test()
        //{ 
        //    //空实现
        //}
    }


    public abstract class Test : Animal
    { 
        
    }

    public class Dog : Animal
    {
       // public abstract void Test();


        public override void Bark()
        {
            Console.WriteLine("狗狗旺旺的叫");
        }

        public override string Name
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        //public override string TestString(string name)
        //{
        //    //throw new NotImplementedException();
        //}
    }

    public class Cat : Animal
    {
        public override void Bark()
        {
            Console.WriteLine("猫咪喵喵的叫");
        }

        public override string Name
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
    }
}

十一、抽象类二

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _12_抽象类
{
    class Program
    {
        static void Main(string[] args)
        {
            //使用多态求矩形的面积和周长以及圆形的面积和周长
            Shape shape = new Square(5, 6); //new Circle(5);
            double area = shape.GetArea();
            double perimeter = shape.GetPerimeter();
            Console.WriteLine("这个形状的面积是{0},周长是{1}", area, perimeter);
            Console.ReadKey();

        }
    }

    public abstract class Shape
    {
        public abstract double GetArea();
        public abstract double GetPerimeter();
    }
    public class Circle : Shape
    {

        private double _r;
        public double R
        {
            get { return _r; }
            set { _r = value; }
        }

        public Circle(double r)
        {
            this.R = r;
        }
        public override double GetArea()
        {
            return Math.PI * this.R * this.R;
        }

        public override double GetPerimeter()
        {
            return 2 * Math.PI * this.R;
        }
    }
    public class Square : Shape
    {
        private double _height;

        public double Height
        {
            get { return _height; }
            set { _height = value; }
        }

        private double _width;

        public double Width
        {
            get { return _width; }
            set { _width = value; }
        }

        public Square(double height, double width)
        {
            this.Height = height;
            this.Width = width;
        }

        public override double GetArea()
        {
            return this.Height * this.Width;
        }

        public override double GetPerimeter()
        {
            return (this.Height + this.Width) * 2;
        }
    }

}

十二、电脑_移动硬盘_U盘_MP3

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _13_电脑_移动硬盘_U盘_MP3
{
    class Program
    {
        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);
            //Console.ReadKey();

            MobileStorage ms = new UDisk();//new Mp3();//new MobileDisk();//new UDisk();
            Computer cpu = new Computer();
            cpu.Ms = ms;
            cpu.CpuRead();
            cpu.CpuWrite();
            //Computer cpu = new Computer();
            //cpu.CpuRead(ms);
            //cpu.CpuWrite(ms);
            Console.ReadKey();

        }
    }


    /// <summary>
    /// 抽象的父类
    /// </summary>
    public abstract class MobileStorage
    {
        public abstract void Read();
        public abstract void Write();
    }


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

        public override void Write()
        {
            Console.WriteLine("U盘在写入数据");
        }
    }
    public class Mp3 : MobileStorage
    {
        public override void Read()
        {
            Console.WriteLine("MP3在读取数据");
        }

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

        public void PlayMusic()
        {
            Console.WriteLine("MP3自己可以播放音乐");
        }
    }



    public class Computer
    {
        private MobileStorage _ms;

        public MobileStorage Ms
        {
            get { return _ms; }
            set { _ms = value; }
        }
        public void CpuRead()
        {
            Ms.Read();
        }

        public void CpuWrite()
        {
            Ms.Write();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南叔先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值