c# 虚方法(virtual)与 多态(Polymorphism)
using System; using System.Collections.Generic; using System.Linq; using System.Text; //虚方法(virtual) //virtual 关键字用于修饰方法、属性、索引器或事件声明,并且允许在派生类中重写这些对象。 //多态(Polymorphism) //多态是指两个或多个属于不同类的对象,对同一个消息做出不同响应的能力。 namespace 虚方法 { class A { public virtual void F() { Console.WriteLine("A.F"); } } class B : A { public override void F() { Console.WriteLine("B.F"); } } class Program { static void Main(string[] args) { B b = new B(); A a = b; a.F(); //"B.F" b.F(); //"B.F" Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 虚方法1 { //员工类 class Employee { protected string _name; public Employee() { } public Employee(string name) { _name = name; } public virtual void StartWork() //虚方法 { Console.Write(_name + "开始工作:"); } } //经理类 class Manager : Employee { //public Manager(string name) //{ // base._name = name; //} //构造函数 public Manager(string name): base(name) //赋值给基类(Employee)构造函数name { } //重写虚方法 public override void StartWork() //使用虚方法实现面向对象的多态 { base.StartWork(); //调用基类的方法 Console.WriteLine("给员工下达任务"); } } //秘书类 class Secretary : Employee { public Secretary(string name) : base(name) { } public override void StartWork() { base.StartWork(); Console.WriteLine("协助经理"); } } //销售类 class Seller : Employee { public Seller(string name) : base(name) { } public override void StartWork() { base.StartWork(); Console.WriteLine("销售产品"); } } //财务类 class Accountant : Employee { public Accountant(string name) : base(name) { } public override void StartWork() { base.StartWork(); Console.WriteLine("管理公司财政"); } } class Program { static void Main(string[] args) { Employee[] emp = new Employee[5]; emp[0] = new Manager("张三"); emp[1] = new Secretary("李四"); emp[2] = new Seller("王五"); emp[3] = new Seller("马六"); emp[4] = new Accountant("钱七"); Console.WriteLine("早上8点,开始工作"); foreach (Employee e in emp) { e.StartWork(); } Console.ReadKey(); } } }