但如果突然在書上看到 Boxing vs. Unboxing 時,這....
雖然 Box & Unbox 跟型態轉型有點類似,但實際上還是有一點差別。主要的差別在於轉型的對象,如果你將特定型(如 int,string...)轉換成 object ,這過程就叫做 Boxing ,反之,如果將 object 轉換成特定型別,就叫做 Unboxing 。
在 MSDN 說得很清楚,對大家來說,比較像是名詞定義而已。
int i=123;
object o = (object)i; //boxing
int j=(int)o; //unboxing
不管是執行 Box 還是 Unbox 動作,都是要耗費運算資源的。
以下針對有進行 Boxing 與 沒有 Boxing 進行了比較:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace boxtest
{
class Program
{
static void Main(string[] args)
{
Stopwatch stop = new Stopwatch();
//啟動計時
stop.Start();
List<object> Box = new List<object>();
//重複 100 萬次
for (int i = 0; i < 1000000; i++)
{
//進行 Boxing 動作
Box.Add((object)i);
}
//停止計時
stop.Stop();
//取得耗時數據
TimeSpan ts = stop.Elapsed;
//啟動計時
stop.Reset();
stop.Start();
List<int> NoBox = new List<int>();
//重複 100 萬次
for (int i = 0; i < 1000000; i++)
{
//沒有進行 Boxing
NoBox.Add(i);
}
//停止計時
stop.Stop();
//取得耗時數據
TimeSpan ts2 = stop.Elapsed;
//列印耗時結果(有 Boxing)
Console.WriteLine("有Boxing...");
Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}:{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10));
//列印耗時結果(沒有 Boxing)
Console.WriteLine("");
Console.WriteLine("沒有Boxing...");
Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}:{3:00}",
ts2.Hours, ts2.Minutes, ts2.Seconds, ts2.Milliseconds / 10));
Console.ReadKey();
}
}
}
於是可以明確知道,有進行 Boxing 的操作,會比沒有 Boxing 的增加 7 倍運算資源。
參考網址:Boxing 和 Unboxing (C# 程式設計手冊)




