C#学习笔记(十四):多态、虚方法和抽象类
虚方法/非虚方法 < 实例方法 = 非静态方法 = 非类方法(非实例方法 = 静态方法 = 类方法)
函数签名(参数列表,或参数列表 + 返回类型)
![](https://img2018.cnblogs.com/blog/1517599/201902/1517599-20190211170522091-2132254438.png)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace m1w3d5_virtual { #region 多态 用虚方法实现 //多态实现 真的鸭子嘎嘎叫,木头鸭子吱吱叫,橡皮鸭子唧唧叫 //多态 不同的实际对象,在同一个指令(叫),有不同的表现 //不同的对象,如何统一管理 里氏转换:可以把子级当父级 如果这些不同的对象全继承自一个父类 //统一管理 如果把子级转换成了父级,子级的特性丢失了 //用虚方法可以 用父级管理并且保留子级的特性 已解决问题 //1,在实例方法前加 virtual //2,在派生类中用 override 重写 同名/同签名的方法 //在一个虚方法被调用时,会根据最后重写的那个方法和实际类型来决定 //不会根据当前类型来执行方法 class Duck { public string name; public virtual void Cry() { Console.WriteLine(",我是{0}", name); } } class TrueDuck : Duck { public TrueDuck() { this.name = "真的鸭子"; } public override void Cry() { Console.Write("嘎嘎"); base.Cry(); } } class WoodDuck : Duck { public WoodDuck() { this.name = "木头鸭子"; } public override void Cry() { Console.Write("吱吱"); base.Cry(); } } class RubberDuck : Duck { public RubberDuck() { this.name = "橡皮鸭子"; } public override void Cry() { Console.Write("唧唧"); base.Cry(); } } // class BeiJingDuck : TrueDuck { public BeiJingDuck() { this.name = "北京烤鸭"; } public override void Cry() { Console.WriteLine("欢迎光临,我是{0}",name); //base.Cry(); } } #endregion #region 多态 练习 //打卡 时间有不同 class Person { public string name; public virtual void PunchCard() { Console.WriteLine(",我是{0}",name); } } class Employee : Person { public Employee() { this.name = "员工"; } public override void PunchCard() { Console.Write("{0},九点打卡", DateTime.Now); base.PunchCard(); } } class Manager : Person { public Manager() { this.name = "经理"; } public override void PunchCard() { Console.Write("{0},十一点打卡", DateTime.Now); base.PunchCard(); } } class Programmer : Person { public Programmer() { this.name = "程序员"; } public override void PunchCard() { Console.Write("{0},不用打卡", DateTime.Now); base.PunchCard(); } } #endregion class Program { static void Main(string[] args) { #region 多态 用虚方法实现 Random roll = new Random(); TrueDuck trueduck = new TrueDuck(); WoodDuck woodduck = new WoodDuck(); RubberDuck ruberduck = new RubberDuck(); trueduck.Cry(); woodduck.Cry(); ruberduck.Cry(); Console.WriteLine(); //当你转换成父类的时候,你会丢失子类的特性 Duck[] ducks = new Duck[10]; for (int i = 0; i < ducks.Length; i++) { int num = roll.Next(0, 150); if (num < 30) { ducks[i] = new RubberDuck(); } else if (num < 60) { ducks[i] = new WoodDuck(); } else if (num < 90) { ducks[i] = new WoodDuck(); } else { ducks[i] = new BeiJingDuck(); } } foreach (var item in ducks) { item.Cry(); } Console.WriteLine(); #endregion #region 多态 练习 //打卡 时间有不同 Employee employee = new Employee(); Manager manager = new Manager(); Programmer programmer = new Programmer(); employee.PunchCard(); manager.PunchCard(); programmer.PunchCard(); Console.WriteLine(); #endregion } } }