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(); }
时间: 2024-10-11 07:24:32