主要区别就是重写可以实现多态,new隐藏不能实现多态。例如- class Person
- {
- public virtual void SayHi()
- {
- Console.WriteLine("人说Hello");
- }
- }
- class Student : Person
- {
- public override void SayHi()
- {
- Console.WriteLine("学生说Hello");
- }
- }
- class Teacher : Person
- {
- public new void SayHi()
- {
- Console.WriteLine("老师说Hello");
- }
- }
复制代码- //父类型的变量指向子类型的对象
- Person person = new Student();
- person.SayHi();
- //运行结果:学生说Hello
- //说明这里调用的是子类重写的方法,实现了多态
- person = new Teacher();
- person.SayHi();
- //运行结果:人说Hello
- //说明这里调用的是父类的方法,没有实现多态
- Console.ReadKey();
复制代码 |