using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 面向对象之多态 { class Program { static void Main(string[] args) { //真的鸭子呱呱叫,木头鸭子吱吱叫,橡皮鸭子唧唧叫 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].Sayhello(); } Console.ReadLine(); } public class RealDuck { public virtual void Sayhello() //注意修饰符 virtual 写在方法前,而不是类前 { Console.WriteLine("真的鸭子呱呱叫"); } } public class MuDuck:RealDuck { public override void Sayhello() { Console.WriteLine("木头鸭子吱吱叫"); } } public class XpDuck:RealDuck { public override void Sayhello() { Console.WriteLine("橡皮鸭子唧唧叫"); } } } }