代码改变世界

override和new在派生类中的区别

2011-05-25 11:15  littlelion  阅读(442)  评论(0编辑  收藏  举报

我在读《把new说透》这一章时,对于new作为修饰符的作用这一部分算是一带而过,没考虑过其具体的作用,也没想过和override的区别究竟在哪,刚才我仔细思考了一下这个问题,又写了代码测试了一下,下面对两者的区别说明一下,主要是理解一下new作为修饰符的作用。

先看一下override的作用吧,众所周知,override用于在派生类中重写基类的虚方法,这种方法的调用发生在运行期,也就是动态的多态性

 

View Code
publicclass MyFunc
{
publicvirtualvoid method(string str)
{
Console.WriteLine(
"虚方法中的str {0}", str);
}
}

publicclass firstFunc : MyFunc
{
publicoverridevoid method(string str)
{
Console.WriteLine(
"复写方法中的str {0}", str);
}
}

publicclass secondFunc : MyFunc
{
publicoverridevoid method(string str)
{
base.method(str); //base用于同基类通信
}
}
class Program
{
staticvoid Main(string[] args)
{
MyFunc B
=new MyFunc();
B.method(
"first"); //调用基类中的方法method

firstFunc A
=new firstFunc();
B
= A; //调用复写方法中的method
B.method("second");

secondFunc C
=new secondFunc();
B
= C;
B.method(
"third");
}
}

输出结果:


实例A复写了基类中的虚方法,实现的是他自己的版本。

再来看看new

 

View Code
publicclass MyFunc
{
publicvirtualvoid method(string str)
{
Console.WriteLine(
"虚方法中的str {0}", str);
}
}

publicclass firstFunc : MyFunc
{
publicnewvoid method(string str)
{
Console.WriteLine(
"复写方法中的str {0}", str);
}
}

publicclass secondFunc : MyFunc
{
publicoverridevoid method(string str)
{
base.method(str); //base用于同基类通信
}
}
class Program
{
staticvoid Main(string[] args)
{
MyFunc B
=new MyFunc();
B.method(
"first"); //调用基类中的方法method

firstFunc A
=new firstFunc();
B
= A; //调用复写方法中的method
B.method("second");

secondFunc C
=new secondFunc();
B
= C;
B.method(
"third");
}
}

输出结果:

可以看到,在子类firstFunc中使用new代替了override后,输出结果变成了父类中的方法,也就是new作为修饰符的作用:用于向基类成员隐藏继承的成员,也就是隐藏派生类的方法,该派生类的方法是独立于其父类的方法的,两者同时存在。这样的感觉就是派生类没有重写基类的那个成员。

如果是有多重继承的情况呢,写代码测试一下就一目了然了。

看一下下面的代码:

View Code
publicclass MyFunc
{
publicvirtualvoid BasicMethod()
{
Console.WriteLine(
"basic method");
}
}

publicclass MyFunc1st : MyFunc
{
publicoverridevoid BasicMethod()
{
Console.WriteLine(
"first method");
}
}

publicclass MyFunc2nd : MyFunc1st
{
publicnewvoid SecondMethod()
{
Console.WriteLine(
"second method");
}
}
class Program
{
staticvoid Main(string[] args)
{
MyFunc A
=new MyFunc();
A.BasicMethod();

MyFunc1st B
=new MyFunc1st();
A
= B;
A.BasicMethod();

MyFunc2nd C
=new MyFunc2nd();
A
= C;
A.BasicMethod();

输出结果:

在这种情况下,基类的成员为搜索继承链,找到使用了new修饰符的那个成员的前面的成员,然后再调用该成员。

在本例中,使用new修饰符的成员的前面的成员复写了基类的虚方法,会输出‘first method’,因此,A会调用这个方法,跟着输出‘first method’,这下就清楚了new作为修饰符的作用了。