C# new和override的区别分析


  本文标签:new,override

   override是指“覆盖”,是指子类覆盖了父类的方法 。子类的对象无法再访问父类中的该方法 。new是指“隐藏”,是指子类隐藏了父类的方法,当然,通过一定的转换,可以在子类的对象中访问父类的方法 。所以说C# new和override的区别是覆盖和隐藏

    以下是代码:

复制代码 代码如下:

<PRE class=csharp name="code">class Base 
{ 
public virtual void F1() 
{ 
Console.WriteLine("Bases virtual function F1"); 
} 
public virtual void F2() 
{ 
Console.WriteLine("Bases virtual fucntion F2"); 
} 
} 
class Derived:Base 
{ 
public override void F1() 
{ 
Console.WriteLine("Deriveds override function F1"); 
} 
public new void F2() 
{ 
Console.WriteLine("Deriveds new function F2"); 
} 
} 
class Program 
{ 
public static void Main(string[] args) 
{ 
Base b1 = new Derived(); 
//由于子类覆盖了父类的方法,因此这里调用的是子类的F1方法 。也是OO中多态的体现 
b1.F1(); 
//由于在子类中用new隐藏了父类的方法,因此这里是调用了隐藏的父类方法 
b1.F2(); 
} 
}