如果在子类中定义了一个与父类完全相同的方法,则子类的方法就会隐藏父类的方法。编译时也会给出一个警告:要求在同名的派生类方法前加上关键字new。如图所示:
参照警告的建议,尝试给子类方法加上关键字new后,警告消失。
①父类代码如下:
class Person
{
public void sayHello()
{
Console.WriteLine("你好,我是人类");
}
}
②子类代码如下:
class Student : Person
{
public new void sayHello()
{
Console.WriteLine("你好,我是学生");
}
}
③主函数尝试调用方法:
class Program
{
static void Main(string[] args)
{
Person per = new Person();
per.sayHello();//调用父类的sayHello()方法
Student stu = new Student();
stu.sayHello();//调用子类的sayHello()方法
Console.ReadKey();
}
}
以上就是new关键字隐藏父类成员的做法。