博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#中Override和New

Posted on 2011-11-01 22:13  Mark.Ma  阅读(147)  评论(0)    收藏  举报

C# 允许派生类包含与基类方法名称相同的方法。

  •  

    基类方法必须定义为 virtual 。

     

  •  

    如果派生类中的方法前面没有 new 或 override 关键字,则编译器将发出警告,该方法将有如存在 new 关键字一样执行操作。

     

  •  

    如果派生类中的方法前面带有 new 关键字,则该方法被定义为独立于基类中的方法。

     

  •  

    如果派生类中的方法前面带有 override 关键字,则派生类的对象将调用该方法,而不调用基类方法。

     

  •  

    可以从派生类中使用 base 关键字调用基类方法。

     

  •  

    override、virtual 和 new 关键字还可以用于属性、索引器和事件中。

     

 

默认情况下,C# 方法不是虚方法 -- 如果将一种方法声明为虚方法,则继承该方法的任何类都可以实现其自己的版本。若要使方法成为虚方法,必须在基类的方法声明中使用 virtual 修饰符。然后,派生类可以使用 override 关键字重写基虚方法,或使用 new 关键字隐藏基类中的虚方法。如果 override 关键字和 new 关键字均未指定,编译器将发出警告,并且派生类中的方法将隐藏基类中的方法。

例1:

 

View Code
public class MyBase 

{

public virtual string Meth1()

{

return "MyBase-Meth1";

}

public virtual string Meth2()

{

return "MyBase-Meth2";

}

public virtual string Meth3()

{

return "MyBase-Meth3";

}

}

class MyDerived : MyBase

{

public override string Meth1()

{

return "MyDerived-Meth1";

}

public new string Meth2()

{

return "MyDerived-Meth2";

}

public string Meth3() // 系统在这里将会有一个警告,并且将会隐藏方法Meth3()

{

return "MyDerived-Meth3";

}



public static void Main()

{

MyDerived mD = new MyDerived();

MyBase mB = (MyBase) mD;



System.Console.WriteLine(mB.Meth1());

System.Console.WriteLine(mB.Meth2());

System.Console.WriteLine(mB.Meth3());

}

}


输出:

MyDerived-Meth1

MyBase-Meth2

MyBase-Meth3

       可以很明显地看出来,后两个new关键字的输出是父类中的方法的输出,所以可以看出,new这个关键字的作用是如果在以前的版本中有这个方法,就沿用以前的方法,而不用我现在方法内容.而virtual的方法的作用正好相反,它的作用是如果在父类中有这样一个方法,则用我现在写的方法内容,让以前的滚蛋!

例2:

public class MyClass1

{

public void a()

{

Console.WriteLine("this is class1''a");

}

public virtual void aa()

{

Console.WriteLine("this is class1''aa");

}

}

public class MyClass2 : MyClass1

{

public new void a()

{

Console.WriteLine("this is class2''a");

}

public override void aa()

{

Console.WriteLine("this is class2''aa");

}

}

public class MyClass3

{

static void Main()

{

MyClass1 c1;

MyClass2 c2;

c1 = new MyClass1();

c1.a();

c1.aa();

Console.WriteLine(c1.GetType().ToString());

c1 = new MyClass2();

c1.a();

c1.aa();

Console.WriteLine(c1.GetType().ToString());

c2 = new MyClass2();

c2.a();

c2.aa();

Console.WriteLine(c2.GetType().ToString());

Console.ReadLine();

}

}


 

输出:

this is class1’a

this is class1’aa

consoleApplication1.MyClass1

this is class1’a

this is class2’aa

consoleApplication1.MyClass2

this is class2’a

this is class2’aa

consoleApplication1.MyClass2

 

virtual方法主要用于重写了基类里的方法,new方法体现了版本控制