C#中virtual 与 override(zz)

C#中virtual 与 override

在C#中,如果你在声明一个方法的时候用了virtual这个关键字,那么,在派生类中,你就可以使用override或者new关键字来弃用它或是忽略它.如果你在父类中用了virtual这个关键字,而在其派生类中又没有用override或new关键字,而直接引用一个同名方法的话,编译器将会报错,并将以new方式,即忽略派生类中的方法的方式来运行.下面的例子可以帮助你来理解:


000: // Versioning\versioning.cs
001: public class MyBase 
002: {
003: public virtual string Meth1() 
004: {
005: return "MyBase-Meth1";
006: }
007: public virtual string Meth2() 
008: {
009: return "MyBase-Meth2";
010: }
011: public virtual string Meth3() 
012: {
013: return "MyBase-Meth3";
014: }
015: }
016: 
017: class MyDerived : MyBase 
018: {
019: public override string Meth1() 
020: {
021: return "MyDerived-Meth1";
022: }
023: public new string Meth2() 
024: {
025: return "MyDerived-Meth2";
026: }
027: public string Meth3() // 系统在这里将会有一个警告,并且将会隐藏方法Meth3() 
028: 
029: 
030: {
031: return "MyDerived-Meth3";
032: }
033: 
034: public static void Main() 
035: {
036: MyDerived mD = new MyDerived();
037: MyBase mB = (MyBase) mD;
038: 
039: System.Console.WriteLine(mB.Meth1());
040: System.Console.WriteLine(mB.Meth2());
041: System.Console.WriteLine(mB.Meth3());
042: }
043: }

输出:

MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3


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

如果你把第037行去掉,把039-041中的mB全部改为mD,输出又变为:

MyDerived-Meth1
MyDerived-Meth2
MyDerived-Meth3

这又说明了什么呢,明了派生类的对象只有在被父类重塑的时候,override和new关键字才会生效.呵呵,这样说的确有点难以理解,大家只有自己动手,才能搞清楚这其中的机关,所谓"实践是检验C#的唯一标准",哈哈!

原文链接:http://annychen1980.spaces.live.com/blog/cns!f3cdbb1d20524f2b!127.entry

posted @ 2006-10-17 18:46  stu_acer  阅读(1088)  评论(0编辑  收藏  举报