1
using System;
2
3
//定义Change方法的接口
4
interface IChangeBoxedPoint
5
{
6
void Change(Int32 x, Int32 y);
7
}
8
9
//让Point值类型实现IChangeBoxedPoint接口
10
struct Point : IChangeBoxedPoint
11
{
12
public Int32 x, y;
13
14
public void Change(Int32 x, Int32 y)
15
{
16
this.x = x;
17
this.y = y;
18
}
19
20
public override string ToString()
21
{
22
return String.Format("({0},{1})", x, y);//{0},{1}-->1,1没有括号
23
}
24
}
25
class App
26
{
27
static void Main()
28
{
29
Point p = new Point();
30
p.x = p.y = 1;
31
Console.WriteLine(p);
32
33
p.Change(2, 2);
34
Console.WriteLine(p);//这里p属于WriteLine重载的哪一种参数 是string?
35
36
Object o = p;
37
Console.WriteLine(o);//output (2,2)
38
39
((Point)o).Change(3, 3);//在栈上改变临时的Point
40
Console.WriteLine(o);//output(2,2)
41
42
Console.WriteLine("------");
43
//对p执行装箱,改变已装箱对象,丢弃该对象
44
((IChangeBoxedPoint)p).Change(4, 4);
45
//Change返回之后,已装箱对象(p)立即成为可被垃圾收集器收集的垃圾对象
46
Console.WriteLine(p);//output(2,2)
47
48
Console.WriteLine("00000000");
49
//由o引用的已装箱形式的Point被转型为一个IChangeBoxedPoint
50
//这里无需装箱,因为o已经是一个已经装箱的Point:Object o=p;
51
((IChangeBoxedPoint)o).Change(5, 5);
52
//接口方法Change允许我们改变一个已装箱Point对象中的字段
53
Console.WriteLine(o);//(5,5)
54
Console.WriteLine(p);//(2,2)
55
56
57
Console.Read();
58
}
59
}

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

49

50

51

52

53

54

55

56

57

58

59
