BoxAndUnbox
1 class Program 2 { 3 // 值类型的反向转换,就是一个unbox, 4 static void Main(string[] args) 5 { 6 int totalCount; 7 ArrayList list = new ArrayList(); 8 9 Console.WriteLine("Enter a number between 2 and 1000:"); 10 totalCount = int.Parse(Console.ReadLine()); 11 12 list.Add((double)0);// box,从 0 封装成double,再转换成一个object对象 13 list.Add((double)1);// box,从 0 封装成double,再转换成一个object对象 14 15 for (int count = 2; count < totalCount; count++) 16 { 17 list.Add((double)list[count - 1] + (double)list[count - 2]);// 2 unbox+1 box,把Object类型的数转换成double类型的数,再进行相加,最后在转换成object类型 18 } 19 20 foreach (double count in list)// unbox,从Object类型转换成double类型。 21 { 22 Console.Write("{0,5}",count);// box,从double类型转换成Object类型。 23 } 24 Console.WriteLine(); 25 Console.WriteLine("----------------------------------------------------"); 26 27 int number; 28 object thing; 29 double bigNumber; 30 31 number = 42; 32 thing = number; 33 34 try 35 { 36 bigNumber = (double)(int)thing; 37 Console.WriteLine(bigNumber); 38 39 } 40 catch (InvalidCastException exception) 41 { 42 Console.WriteLine("异常信息:{0},The Log is {1}",exception.Message,exception.Source); 43 } 44 } 45 }