题目描述
类的多态。(控制台应用程序)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { class Program { static void Main(string[] args) { Clerk myClerk = new Clerk(); ProjectManagent myPM = new ProjectManagent(); Clerk[] clerk = { myClerk, myPM }; foreach (Clerk outclerk in clerk) outclerk.WorkPlan(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { class Clerk { public virtual void WorkPlan() { Console.WriteLine("我是职员,我需要有工作计划"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { class ProjectManagent:Clerk { public override void WorkPlan() { Console.WriteLine("我是项目经理,我也需要有工作计划"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { class Program { static void Main(string[] args) { Drink myMilk = new Milk();//抽象类是不允许创建实例的 Drink myTea = new Tea(); Drink[] drink = { myMilk, myTea }; foreach(Drink outdrink in drink) outdrink.drink(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { abstract class Drink { public abstract void drink(); //利用抽象来实现,类抽象化,方法抽象化,并且方法中不能有方法体 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { class Milk:Drink { public override void drink() { Console.WriteLine("我是牛奶,我可以解渴"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 类的多态 { class Tea:Drink { public override void drink() { Console.WriteLine("我是茶,我可以解渴"); } } }
***在C#中可以通过多种途径实现多态性
A.虚方法:将父类的方法标记为虚方法,使用关键字virtual,此方法在子类中可以重写(使用关键字override)
B.抽象类与抽象方法:如果我们不需要使用父类创建对象。它的存在只是为供子类继承。可以将父类写成抽象(关键字abstract)类,将父类方法写成抽象方法,子类中的方法仍然使用关键字override重写。
C.接口实现。
我们选择使用虚方法还是抽象类抽象方法实现多态,取决于我们是否需要使用基类实例化的对象。
抽象类:不需要使用基类实例化的对象
虚方法:需要使用基类实例化的对象