// 非泛型集合包裝 int
public class IntCollection : IList
{
private ArrayList _list = new ArrayList();
public int this[int i] => (int)_list[i]; // 拆箱
public int Add(int item) { _list.Add(item); return _list.Count-1; } // 裝箱
}
static void Main() { IntCollection c = new IntCollection(); c.Add(5); int i = c[0]; }
少量資料影響微小,但大量值型別 (int、double、struct) 時,頻繁裝箱/拆箱造成 **堆積壓力、GC 負擔、效能下降**。
static void Main()
{
List list = new List();
list.Add(5); // 無裝箱
int i = list[0]; // 無拆箱
}
IL 碼可驗證:泛型版本直接操作值型別,無 box/unbox 指令。
static void Swap(ref T a, ref T b)
{
Console.WriteLine($"Type: {typeof(T)}");
T tmp = a; a = b; b = tmp;
}
public class Point
{
private T _x, _y;
public T X { get => _x; set => _x = value; }
public T Y { get => _y; set => _y = value; }
public override string ToString() => $"[{_x}, {_y}]";
}
同類別語法,將 class 改為 struct,適用於小型值型別 (座標、複數、矩陣等),避免堆積配置。