利用接口来改变已装箱值类型中的字段

 1using System;
 2
 3//定义Change方法的接口
 4interface IChangeBoxedPoint
 5{
 6    void Change(Int32 x, Int32 y);
 7}

 8
 9//让Point值类型实现IChangeBoxedPoint接口
10struct 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}

25class 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(22);
34        Console.WriteLine(p);//这里p属于WriteLine重载的哪一种参数 是string?
35
36        Object o = p;
37        Console.WriteLine(o);//output (2,2)
38
39        ((Point)o).Change(33);//在栈上改变临时的Point
40        Console.WriteLine(o);//output(2,2)
41
42        Console.WriteLine("------");
43        //对p执行装箱,改变已装箱对象,丢弃该对象
44        ((IChangeBoxedPoint)p).Change(44);
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(55);
52        //接口方法Change允许我们改变一个已装箱Point对象中的字段
53        Console.WriteLine(o);//(5,5)
54        Console.WriteLine(p);//(2,2)
55
56
57        Console.Read();
58    }

59}

posted on 2007-07-16 22:44  simhare  阅读(229)  评论(0编辑  收藏  举报

导航