关于virtual & Override & new
1, override用于在派生类中重写一个函数, 需要和virtual一起使用 (主要不同在于13,14行的结果)
1 namespace TryNewVirtualOverride 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Parent p = new Parent(); 8 p.DoSomething(); 9 10 Son s = new Son(); 11 s.DoSomething(); 12 13 Parent ps = new Son(); 14 ps.DoSomething(); 15 16 Console.Read(); 17 } 18 } 19 20 class Parent 21 { 22 public virtual void DoSomething() 23 { 24 Console.WriteLine("parent does something"); 25 } 26 } 27 28 class Son : Parent 29 { 30 public override void DoSomething() 31 { 32 Console.WriteLine(); 33 Console.WriteLine("son does something"); 34 } 35 } 36 }
结果

2, new 用来隐藏基类的方法。
如果签名相同的方法在基类和派生类都进行了声明,但该方法没有声明为virtual和override,派生类会应藏基类方法,但是会有一个编译警告,需要加一个new关键字消除警告,但是结果相同。
1 namespace TryNewVirtualOverride 2 { 3 class Program 4 { 5 static void Main(string[] args) 6 { 7 Parent p = new Parent(); 8 p.DoSomething(); 9 10 Son s = new Son(); 11 s.DoSomething(); 12 13 Parent ps = new Son(); 14 ps.DoSomething(); 15 16 Console.Read(); 17 } 18 } 19 20 class Parent 21 { 22 public void DoSomething() 23 { 24 Console.WriteLine("parent does something"); 25 } 26 } 27 28 class Son : Parent 29 { 30 public new void DoSomething() 31 { 32 Console.WriteLine(); 33 Console.WriteLine("son does something"); 34 } 35 } 36 }
结果

如果没有new,出现的警告如下

浙公网安备 33010602011771号