装箱、拆箱练习

【示例代码】

 1 using System;
 2 //Point is a Value Type
 3 internal struct Point {
 4     private Int32 m_x, m_y;
 5 
 6     public Point(Int32 x,Int32 y){
 7         m_x = x;
 8         m_y = y;
 9     }
10 
11     public void Change(Int32 x, Int32 y){
12         m_x = x;
13         m_y = y;
14     }
15 
16     public override String ToString(){
17         return String.Format("({0}, {1})",m_x, m_y);
18     }
19 
20     public sealed class Program {
21         public static void Main(){
22             Point p = new Point(1, 1);
23 
24             Console.WriteLine(p); //1,1 有装箱操作Console.WriteLine(Object)
25 
26             p.Change(2, 2);
27             Console.WriteLine(p); //2,2 有装箱操作Console.WriteLine(Object)
28 
29             Object o = p; //有装箱操作
30             Console.WriteLine(o); //2,2 无装箱
31              
32              ((Point) o).Change(3, 3); //拆箱并将Point对象复制到栈上临时变量中,并执行Change方法
33              Console.WriteLine(o); //2,2
34         }
35     }
36 }
posted @ 2015-05-08 17:20  lishidefengchen  阅读(157)  评论(0编辑  收藏  举报