继承(父类为虚方法以及子类的重写)
定义父类为虚方法时需要关键字 virtual
子类重写需要关键字 override
示例代码:
//父类
public class People
{
//虚方法
//VR Virtual Reality 虚拟现实
//AR Augmented Reality 增强现实
public virtual void SayHello()
{
Console.WriteLine("父类打招呼的方法");
}
}
//子类(重写父类方法)
public class Chinese:People
{
public override void SayHello()
{
Console.WriteLine("你好!");
}
}
//子类
public class American:People
{
public override void SayHello()
{
Console.WriteLine("Hello");
}
}
public static void Main(string[] args)
{
//统一调用
List<People> list = new List<People>()
{
new Chinese(),
new American()
};
People people = new People();
people.SayHello();
foreach (People item in list)
{
item.SayHello();
}
Console.ReadKey();
}