C# new和override的区别分析

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

  以下是代码:

  

复制代码 代码如下:

  <PRE class=csharp name="code">class Base

  {

  public virtual void F1()

  {

  Console.WriteLine("Base's virtual function F1");

  }

  public virtual void F2()

  {

  Console.WriteLine("Base's virtual fucntion F2");

  }

  }

  class Derived:Base

  {

  public override void F1()

  {

  Console.WriteLine("Derived's override function F1");

  }

  public new void F2()

  {

  Console.WriteLine("Derived's new function F2");

  }

  }

  class Program

  {

  public static void Main(string[] args)

  {

  Base b1 = new Derived();

  //由于子类覆盖了父类的方法,因此这里调用的是子类的F1方法。也是OO中多态的体现

  b1.F1();

  //由于在子类中用new隐藏了父类的方法,因此这里是调用了隐藏的父类方法

  b1.F2();

  }

  }