C#学习记录3下——类的封装,继承,多态
new,virtual,override三者的区别
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Example 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Shape shap1 = new Shape(); 14 shap1.Draw(); 15 Polygon poly1 = new Polygon(); 16 poly1.Draw(); 17 Rectangle rect1 = new Rectangle(); 18 rect1.Draw(); 19 Shape polyAsShape = new Polygon(); 20 polyAsShape.Draw(); 21 Shape rectAsShape = new Rectangle(); 22 rectAsShape.Draw(); 23 Polygon rectAsPoly = new Rectangle(); 24 rectAsShape.Draw(); 25 Console.ReadKey(); 26 } 27 class Shape 28 { 29 public virtual void Draw() 30 { 31 Console.WriteLine("Inside Shape"); 32 } 33 } 34 class Polygon : Shape 35 { 36 public new virtual void Draw() 37 { 38 Console.WriteLine("Inside Polygon"); 39 } 40 } 41 class Rectangle : Polygon 42 { 43 public virtual void Draw() 44 { 45 Console.WriteLine("Inside Rectangle"); 46 } 47 } 48 } 49 }
从上面的结果可以看出
通过new定义的子类方法,如果子类的具体实例是子类类型(poly1),则调用子类中的重写函数;子类实例是父类类型(即polyAsShape),则调用父类中的重写函数。
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Example 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Shape shap1 = new Shape(); 14 shap1.Draw(); 15 Polygon poly1 = new Polygon(); 16 poly1.Draw(); 17 Rectangle rect1 = new Rectangle(); 18 rect1.Draw(); 19 Shape polyAsShape = new Polygon(); 20 polyAsShape.Draw(); 21 Shape rectAsShape = new Rectangle(); 22 rectAsShape.Draw(); 23 Polygon rectAsPoly = new Rectangle(); 24 rectAsShape.Draw(); 25 Console.ReadKey(); 26 } 27 class Shape 28 { 29 public virtual void Draw() 30 { 31 Console.WriteLine("Inside Shape"); 32 } 33 } 34 class Polygon : Shape 35 { 36 public override void Draw() 37 { 38 Console.WriteLine("Inside Polygon"); 39 } 40 } 41 class Rectangle : Polygon 42 { 43 public override void Draw() 44 { 45 Console.WriteLine("Inside Rectangle"); 46 } 47 } 48 } 49 }
上面的结果说明
override无论子类的实例是父类类型还是子类类型,子类的实例都会调用子类中重写的函数。其实override可以对父类的所有方法进行覆盖,不一定是virtual