Chapter 8. 面向对象(多态--虚方法)
Posted 庚xiao午
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Chapter 8. 面向对象(多态--虚方法)相关的知识,希望对你有一定的参考价值。
namespace 多态 { 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() { Console.WriteLine("我是人类"); } } public class Chinese : Person { public Chinese(string name) : base(name) { } //方法重写 public override void SayHello() { 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 Korean : Person { public Korean(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); } } public class Englishman : Person { public Englishman(string name) : base(name) { } //方法重写 public override void SayHello() { Console.WriteLine("我是英国人,我叫{0}", this.Name); } } }
class Program { static void Main(string[] args) { Chinese cn1 = new Chinese("程家阳"); Chinese cn2 = new Chinese("王旭东"); Japanese j1 = new Japanese("树下君"); Japanese j2 = new Japanese("井边子"); Korean k1 = new Korean("金秀贤"); Korean k2 = new Korean("李钟硕"); American a1 = new American("阿黛尔"); American a2 = new American("小甜甜布兰妮"); Person[] p = { cn1, cn2, j1, j2, k1, k2, a1, a2, new Englishman("格林"),new Englishman("玛利亚") }; for (int i = 0; i < p.Length; i++) { p[i].SayHello(); } Console.ReadLine(); }
以上是关于Chapter 8. 面向对象(多态--虚方法)的主要内容,如果未能解决你的问题,请参考以下文章