首先看下面的代碼:
? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17using System;
namespace Test
{
public
class
Base
{
public
void
Print()
{
Console.WriteLine(Operate(
8
,
4
));
}
protected
virtual
int
Operate(
int
x,
int
y)
{
return
x + y;
}
}
}
?
1
2
3
4
5
6
7
8
9
10
namespace Test
{
public
class
OnceChild : Base
{
protected
override
int
Operate(
int
x,
int
y)
{
return
x - y;
}
}
}
?
1
2
3
4
5
6
7
8
9
10
namespace Test
{
public
class
TwiceChild : OnceChild
{
protected
override
int
Operate(
int
x,
int
y)
{
return
x * y;
}
}
}
?
1
2
3
4
5
6
namespace Test
{
public
class
ThirdChild : TwiceChild
{
}
}
?
1
2
3
4
5
6
7
8
9
10
namespace Test
{
public
class
ForthChild : ThirdChild
{
protected
new
int
Operate(
int
x,
int
y)
{
return
x / y;
}
}
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace Test
{
class
Program
{
static
void
Main(string[] args)
{
Base b =
null
;
b =
new
Base();
b.Print();
b =
new
OnceChild();
b.Print();
b =
new
TwiceChild();
b.Print();
b =
new
ThirdChild();
b.Print();
b =
new
ForthChild();
b.Print();
}
}
}
看結果:
從結果中可以看出:使用override重寫之後,調用的函數是派生的最遠的那個函數,使用new重寫則是調用new之前的派生的最遠的函數,即把new看做沒有重寫似的。