读《clr via c# 》笔记
误解
在本书的Chapter 2中,在GetType方法的描述中有这样一句话:
"The GetType Method is nonvirtual,which prevents a class from overrding this method and lying about its type,violating type safety"
翻译过来就是:GetType方法是一个非虚方法,不能重写此方法所以也就不能伪装成另一个类而违反类型安全。 一直不明白这句话的意思,非虚化方不
能被重写,那么new呢?它又是怎么回事?
什么叫隐藏?
上面说道new只是隐藏了积累成员的实现,但是这里的隐藏到底是什么意思呢?这就不得不说override与new的用法。下面用实例来说明一下什么叫隐藏。
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 B b = new B();
6 Console.ReadLine();
7 }
8
9 }
10
11 public class A
12 {
13 public A()
14 {
15 PrintSomeThingToScreen();
16 }
17
18 public virtual void PrintSomeThingToScreen() { Console.WriteLine("这是父类"); }
19
20 }
21
22 public class B : A
23 {
24 int x = 1;
25 int y;
26 public B()
27 {
28 y = 10;
29 }
30 public override void PrintSomeThingToScreen()
31 {
32 Console.WriteLine("x={0},y={1}", x, y);
33 }
34 }
上述代码非常简单,相信多数人都可以看明白,很多初级程序员面试的时候都会有类似的代码。
输出为:
B类在实例化的时候执行顺序是:类A的构造函数->B的PrintSomeThingToScreen方法->B的构造函数。
假如我们把virtual去掉,那么就要把B类的PrintSomeThingToScreen加上new关键字。
代码就变成了下面这样:
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 B b = new B();
6 Console.ReadLine();
7 }
8
9 }
10
11 public class A
12 {
13 public A()
14 {
15 PrintSomeThingToScreen();
16 }
17
18 public void PrintSomeThingToScreen() { Console.WriteLine("这是父类"); }
19
20 }
21
22 public class B : A
23 {
24 int x = 1;
25 int y;
26 public B()
27 {
28 y = 10;
29 }
30 public new void PrintSomeThingToScreen()
31 {
32 Console.WriteLine("x={0},y={1}", x, y);
33 }
34 }
输出就变成了:

上面的顺序就变成了:类A的构造函数->A的PrintSomeThingToScreen方法->B的构造函数。
所以说new 关键字可以显式隐藏从基类继承的成员。隐藏继承的成员时,该成员的派生版本将替换基类版本。
如果是override呢?那就是派生类的版本将还是自己的。
浙公网安备 33010602011771号