总结:ide
1. 在继承上, new/override没区别spa
2. 在多态上,new不支持多态,override支持3d
在C#中改变类中相同名称的方法的实现过程当中有三种方式:重载、重写和覆盖。 code
重载:指具备相同的方法名,经过改变参数的个数或者参数类型实现同名方法的不一样实现。blog
重写:则是只在继承中,子类经过override关键字修饰方法,实现父类和子类相同方法的不一样实现,注意,父类方法必须是用virtual或者abstract关键字修饰的虚方法或者抽象方法继承
覆盖:则是指在继承中,子类经过在与父类相同方法名以前用new修饰的一个新的方法的定义string
1.new ---- 子类隐藏父类的方法,覆盖(总结:new关键字不支持多态)
it
下面的例子咱们能够发现new 关键字,并不支持多态的应用io
咱们使用多态调用的任然仍是父类中的方法,也就是被隐藏的方法class
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Father fa = new Son(); fa.print(); } } class Father { public void print() { Console.WriteLine("我是父类"); } } class Son : Father { public new void print() { Console.WriteLine("我是子类"); } } }
输出:
若是咱们使用了多态建立了实例,要调用子类重写的方法,须要强制转换成子类类型,实例以下:
class Program { static void Main(string[] args) { Father fa = new Son(); Son so = (Son)fa; so.print(); } }
输出:
2.virtual-- 重写 abstract--实现 (总结:这两种都支持多态)
a.重写父类的方法要用到override关键字(具备override关键字修饰的方法是对父类中同名方法的新实现)
b.要重写父类的方法,前提是父类中该要被重写的方法必须声明为virtual或者是abstract类型。(virtual修饰的能够有方法体,子类不必定要重写 abstract没有方法体,子类必需要实现)
C.virtual关键字用于将方法定义为支持多态,有virtual关键字修饰的方法称为“虚拟方法”
实例以下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Father fa = new Son(); fa.print(); } } class Father { public virtual void print() { Console.WriteLine("我是父类"); } } class Son : Father { public override void print() { Console.WriteLine("我是子类"); } } }
输出:
