多态之虚方法步骤
1)将父类的方法标记为虚方法,使用关键词virtual,这个函数可以被子类重新写一遍,override将子类标记;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01多态//实现多态的三种方法:抽象类、虚方法、接口
{
class Program
{
static void Main(string[] args)
{
//概念:让一个对象能够表现多重的状态(类型)
Chinese chinese = new Chinese("刘德华");
Japanese japanese = new Japanese("苍井空");
Korea korea = new Korea("金秀贤");
Person[] pers = new Person[3] { chinese, japanese, korea };
for (int i = 0; i < pers.Length; i++)
{
pers[i].SayHello();//输出全是我是人类
// if(pers[i] is Chinese)
// {
// ((Chinese)pers[i]).SayHello();
// }
// else if (pers[i] is Japanese)
// {
// ((Japanese)pers[i]).SayHello();
// }
// else
// {
// ((Korea)pers[i]).SayHello();
// }
}//解决代码冗余
Console.ReadKey();
}
}
public class Person
{
private string _name;//字段
public string Name//属性
{
get => _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 Korea : Person
{
public Korea(string name) : base(name)//父类构造函数
{
}
public override void SayHello()
{
Console.WriteLine("我是韩国人,叫{0}", this.Name);
}
}
}