C#中多态的实现

因为能够继承基类的全部成员,子类就都有了相同的行为,可是有时子类的某些行为须要相互区别,而子类须要覆盖父类的方法来实现子类特有的行为,这就是所谓的多态,多态即相同类型的对象调用相同的方法却表现出不一样行为的现象。ide

一.实现多态的两种常见方式spa

(1).虚方法(virtual):将父类的方法,添加关键字virtual,此方法在子类中用override重写。code

(2).抽象类与抽象方法(abstarct):有时候基类的做用只是为子类提供公共成员,没有具体的实现操做,那么此时能够将基类及其方法定义为抽象的。子类中的方法仍用override重写。对象

 

二.虚方法(virtual)的使用blog

咱们知道比较有名的车,有宝马,奔驰等,能够从它们中抽象出一个汽车基类,而宝马车,奔驰车做为子类继承

(1).基类string

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { public class Car { public virtual void carName() { Console.WriteLine("这是汽车"); } } }

(2).子类it

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { public class BaoMa:Car { public override void carName() { //base.carName();
            Console.WriteLine("这是宝马汽车"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { public class BenChi:Car { public override void carName() { //base.carName();
            Console.WriteLine("这是奔驰汽车"); } } }

(3).调用io

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { class Program { static void Main(string[] args) { Car car = new Car(); BenChi benChi = new BenChi(); BaoMa baoMa = new BaoMa(); Car[] cars = { car, benChi, baoMa }; foreach (Car c in cars) { c.carName(); } Console.ReadKey(); } } }

打印结果:class

三.关键字abstract实现多态

动物分不少种,好比说牛,马等,但它们发出的声音都是不相同的。

(1).基类

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { public abstract class Animal { //动物声音
        public abstract void Voice(); } }

(2).子类

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { class Horse:Animal { //马的声音
        public override void Voice() { Console.WriteLine("马的声音"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { class Cattle:Animal { //牛的声音
        public override void Voice() { Console.WriteLine("牛的声音"); } } }

(3).调用

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Polymorphic { class Program { static void Main(string[] args) { Horse horse = new Horse(); Cattle cattle = new Cattle(); Animal[] animals = { horse, cattle }; foreach (Animal animal in animals) { animal.Voice(); } Console.ReadKey(); } } }

打印结果:

相关文章
相关标签/搜索