new关键字用作修饰符

用new修饰的方法,在编译期按变量类型调用

所以:

Number number = new IntNumber();
number.ShowInfo();

会显示”base class—“

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Number
{
public static int i = 123;

public virtual void ShowInfo()
{
Console.WriteLine("base class---");
}

public virtual void ShowNumber()
{
Console.WriteLine(i.ToString());
}
}

class IntNumber : Number
{
new public static int i = 456;

public new virtual void ShowInfo()
{
Console.WriteLine("Derived class---");
}

public override void ShowNumber()
{
Console.WriteLine("Base number is {0}", Number.i.ToString());
Console.WriteLine("New number is {0}", i.ToString());
}
}

class Test_Number
{
public static void Main() //Main_6_1_1
{
Number num = new Number();
num.ShowNumber();
IntNumber intNum = new IntNumber();
intNum.ShowNumber();
intNum.ShowInfo();
Number number = new IntNumber();
//究竟调用了谁?
number.ShowInfo();
//究竟调用了谁?
number.ShowNumber();
Console.Read();
}
}