首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 泛型介紹(二):避免裝箱拆箱、泛型方法/類別實作與效能優勢

     編輯:關於C語言

傳統集合的裝箱/拆箱代價


// 非泛型集合包裝 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 負擔、效能下降**。

泛型 List 完全避免裝箱/拆箱


static void Main()
{
    List list = new List();
    list.Add(5);   // 無裝箱
    int i = list[0]; // 無拆箱
}

IL 碼可驗證:泛型版本直接操作值型別,無 box/unbox 指令。

泛型三種定義形式

1. 泛型方法


static void Swap(ref T a, ref T b)
{
    Console.WriteLine($"Type: {typeof(T)}");
    T tmp = a; a = b; b = tmp;
}

2. 泛型類別


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}]";
}

3. 泛型結構

同類別語法,將 class 改為 struct,適用於小型值型別 (座標、複數、矩陣等),避免堆積配置。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved