首页 > 代码库 > 继承 通过虚方法实现多态
继承 通过虚方法实现多态
多态:即多种表现形态
首先定义一个Person父类
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{ /// <summary> /// 父类 /// </summary> public class Person { /// <summary> /// 姓名 /// </summary> public string Name { get; set; } public Person(string name) { this.Name = name; } public virtual void Show() { Console.WriteLine("父类中的方法"); } }}
然乎建立几个子类继承自父类
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{ /// <summary> /// 中国人类 /// </summary> public class Chinese : Person { public Chinese(string name) : base(name) { } public override void Show() { Console.WriteLine("我是{0},我是中国人", Name); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{ public class Japanese : Person { public Japanese(string name) : base(name) { } public override void Show() { Console.WriteLine("我是{0},我是日本人", Name); } }}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{ public class American : Person { public American(string name) : base(name) { } public override void Show() { Console.WriteLine("我叫{0},我是美国人", Name); } }}
效果
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp{ class Program { static void Main(string[] args) { Chinese ch1 = new Chinese("孙磊"); Chinese ch2 = new Chinese("大海"); Japanese jp1 = new Japanese("安倍"); Japanese jp2 = new Japanese("苍井空"); American am1 = new American("奥巴马"); American am2 = new American("Microsoft"); Person[] per = new Person[] { ch1, ch2, jp1, jp2, am1, am2 }; for (int i = 0; i < per.Length; i++) { #region MyRegion //if (per[i] is Chinese) //{ // Chinese ch = (Chinese)per[i]; // ch.Show(); //} //else if (per[i] is Japanese) //{ // Japanese jp = (Japanese)per[i]; // jp.Show(); //} //else if (per[i] is American) //{ // American am = (American)per[i]; // am.Show(); //} #endregion per[i].Show(); } Console.ReadKey(); } }}
继承 通过虚方法实现多态
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。