class Program { static void Main(string[] args) { Pet dog = new Dog("DD");//创建指向派生类Dog的基类Pet的实例 dog.Speak();//此处是调用Pet类的虚方法Speak(),根据dog所指向的派生类Dog而调用Dog里的同名重写方法Speak()---即多态 Pet cat = new Cat("CC");//创建指向派生类Cat的基类Pet的实例 cat.Speak();//此处是调用Pet类的虚方法Speak(),根据cat所指向的派生类Cat而调用Cat里的同名重写方法Speak()---即多态 } } public class Pet { protected string Name;//protected 保护级别,派生类可访问 public Pet(string name)//基类的构造函数 { Name = name; } public void PrintName() { Console.WriteLine("Print"+Name); } virtual public void Speak() { Console.WriteLine("I'm "+Name); } } public class Dog : Pet { public Dog(string name):base(name)//构造函数//用关键字base调用了基类的构造函数 { } new public void PrintName() { Console.WriteLine("子打印"+base.Name);//此处Name是Pet.Name } override public void Speak()//重写基类Pet的虚方法 { Console.WriteLine("子说" + Name); } } public class Cat : Pet { public Cat(string name):base(name)//构造函数//用关键字base调用了基类的构造函数 { } new public void PrintName() { Console.WriteLine("子打印" + Name);//此处Name是Pet.Name } override public void Speak()//重写基类Pet的虚方法 { Console.WriteLine("子说" + Name); } }