代码改变世界

2.11

2017-09-26 09:31  xx--  阅读(250)  评论(0编辑  收藏  举报

 

 

 

 

new与override的区别:

在子类中用 new 关键字修饰 定义的与父类中同名的方法,叫覆盖。 覆盖不会改变父类方法的功能。

用关键字 virtual 修饰的方法,叫虚方法。可以在子类中用override 声明同名的方法,这叫“重写”。相应的没有用virtual修饰的方法,我们叫它实方法。
重写会改变父类方法的功能。

当用子类创建父类的时候,如 C1 c3 = new C2(),重写会改变父类的功能,即调用子类的功能;而覆盖不会,仍然调用父类功能。

 

Animal.cs:

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

namespace Test
{
    class Animal                     //创建基类
    {
        private bool m_sex;
        private string m_sound;
        public bool Sex { get { return m_sex; } set { m_sex = value; } }
        public string Sound { get { return m_sound; } set { m_sound = value; } }
        public Animal()
        {
            Sound = "Howl...";
        }
        public virtual string Roar()
        {
                return "";     
        }
    }
    class Dog:Animal               //创建派生类并继承Animal
    {
        public Dog()
        {
            Sex = true;
            Sound = "Wow...";
        }
        public override string Roar()        //重写Roar函数
        {
            return "Dog:" + Sound;
        }
    }
    class Cat : Animal                           //创建派生类并继承Animal
    {
        public Cat()
        {
            Sound = "Miaow...";
        }
        public override string Roar()           //重载Roar函数
        {
            return "Cat:" + Sound;
        }
    }
    class Cow : Animal                           //创建派生类并继承Animal
    {
        public Cow()
        {
            Sound = "Moo...";
        }
        public override string Roar()           //重载Roar函数
        {
            return "Cow:" + Sound;
        }
    }

}



 Program.cs:

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

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Animal animal = new Animal();             //分别创建父类及子类对象并将子类对象赋给父类对象,由于使用“重写”父类对象将调用子类Roar函数
            Dog dog = new Dog();
            animal = dog;
            Console.WriteLine(animal.Roar());
            Cat cat = new Cat();
            animal = cat;
            Console.WriteLine(animal.Roar());
            Cow cow = new Cow();
            animal = cow;
            Console.WriteLine(animal.Roar());
            Console.WriteLine("按回车键结束");
            Console.ReadLine();
        }
    }
}