首页 > 代码库 > 多态之虚方法
多态之虚方法
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication4{ class Program { static void Main(string[] args) { Chinese c1 = new Chinese("韩梅梅"); Chinese c2 = new Chinese("李雷"); Japanese j1 = new Japanese("树下"); Japanese j2 = new Japanese("田中"); Korea k1 = new Korea("金秀贤"); Korea k2 = new Korea("金秀贤2"); American a1 = new American("科比1"); American a2 = new American("科比2"); Person[] pers = {c1,c2,j1,j2,k1,k2,a1,a2}; for (int i = 0; i < pers.Length; i++) { //if(pers[i] is Chinese) //{ // ((Chinese)pers[i]).SayHello(); //} //else if(pers[i] is Japanese) //{ // ((Japanese)pers[i]).SayHello(); //} //else if(pers[i] is Korea) //{ // ((Korea)pers[i]).SayHello(); //} //else if(pers[i] is American) //{ // ((American)pers[i]).SayHello(); //} pers[i].SayHello(); } Console.ReadKey(); } } public class Person { private string _name;//字段 public string Name//属性 { get{return _name;} set{_name = value;} } public Person(string name)//构造函数 { this.Name = name; } public virtual void SayHello()//方法 virtual 虚方法,这个方法可以被子类重写 { Console.WriteLine("我是人类"); } } public class Chinese:Person { public Chinese(string name):base(name) //调用父类构造函数,外面传进一个name,传给父类一个name { //不用写代码,父类的构造器已经赋值给属性Name } public override void SayHello()//override重写 父类方法 { Console.WriteLine("我是中国人,我叫{0}",this.Name); } } public class Japanese:Person { public Japanese(string name) :base(name) { } public override void SayHello() { Console.WriteLine("我是霓虹人,我叫{0}",this.Name); } } public class Korea:Person { public Korea(string name) :base(name) { } public override void SayHello() { Console.WriteLine("我是棒子人,我叫{0}",this.Name); } } public class American:Person { public American(string name) :base(name) { } public override void SayHello() { Console.WriteLine("我是米国人,我叫{0}",this.Name); } }}
多态之虚方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。