二、.NET基础概念《面向对象-多态》
1.虚方法(virtual)
---override(方法重写)
static void Main(string[] args)
{
Person per = new Person();
per.sayNationality();
Person per1 = new American();
per1.sayNationality();
Person per2 = new Chinese();
per2.sayNationality();
Person per3 = new Jananese();
per3.sayNationality();
Console.ReadLine();
}
public class Person
{
/// <summary>
/// 虚方法
/// </summary>
public virtual void sayNationality()
{
Console.WriteLine("地球人");
}
}
public class Chinese:Person
{
public override void sayNationality()
{
Console.WriteLine("中国");
}
}
public class American : Person
{
public override void sayNationality()
{
Console.WriteLine("美国");
}
}
public class Jananese : Person
{
public override void sayNationality()
{
Console.WriteLine("日本");
}
}
}
2.创建同父类相同的方法,如果不适用 override 覆盖,需要使用 new 关键字重新生成一个新的方法(当然也可以不写,默认为new),此时这个类只有一个新方法,无法继承父类的方法,相当于创建的虚方法无效。但是可以通过 base. 方法调用到父类的方法
---new(方法新建)
static void Main(string[] args)
{
Person per = new Person();
per.sayNationality();
Person per1 = new Chinese();
per1.sayNationality(); //此时不会调用Chinese类的方法,打印的是地球人
((Chinese)per2).sayNationality(); //此时会调用Chinese类的方法,打印的是中国
}
public class Person
{
/// <summary>
/// 虚方法
/// </summary>
public virtual void sayNationality()
{
Console.WriteLine("地球人");
}
}
public class Chinese:Person
{
public new void sayNationality()
{
Console.WriteLine("中国");
}
}