C#---装箱、拆箱的一个案例

 1 using System;
 2 
 3 namespace ConsoleApplication1
 4 {
 5     interface IInterface
 6     {
 7         void Add(int num);
 8     }
 9 
10     struct Test : IInterface
11     {
12         public int num;
13         public Test(int _num)
14         {
15             num = _num;
16         }
17 
18         public void Add(int _num)
19         {
20             num += _num;
21         }
22     }
23 
24     class Program
25     {
26         static void Main(string[] args)
27         {
28             Test test = new Test(7);
29 
30             IInterface interTest = test; //在堆上创建一个包含值(test)的对象(即一个普通的对象,该对象的值是原始值的一个副本),interTest的值是对该新对象的一个引用
31             interTest.Add(5);
32  
33             Console.WriteLine(test.num);  // 7
34 
35             int a = 55;
36             object obj = a; //在堆上创建一个包含值(55)的对象(即一个普通的对象,该对象的值是原始值的一个副本).obj的值是对该新对象的一个引用
37             obj = 12;
38             Console.WriteLine(a);        //55
39 
40             Console.ReadKey();
41         }
42     }
43 }

猜你喜欢

转载自www.cnblogs.com/luguoshuai/p/10673287.html