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

C# 陣列與集合進階:自訂型別陣列與集合選型指南

     編輯:關於C語言

自訂型別陣列

定義類別 `User` 並建立陣列:


public class User
{
    private string _name;
    public string Name { get => _name; set => _name = value; }
}

class Program
{
    static void Main()
    {
        User[] users = new User[2];
        var u = new User { Name = "Beniao" };
        users[0] = u;
        Console.WriteLine(users[0].Name); // Beniao
    }
}
自訂型別陣列示意圖

多維/鋸齒/Array 陣列

實務較少用,簡述:

  • 多維:`int[,] matrix = new int[3,4];`
  • 鋸齒:`int[][] jagged = new int[3][];` 每列長度可不同
  • `System.Array`:所有陣列基底類別,提供靜態方法 `Sort`、`Copy`、`IndexOf` 等

集合物件總覽

.NET 集合分類:

分類命名空間代表類別特點
非泛型System.CollectionsArrayList, Queue, Stack, Hashtable元素為 object,需裝箱
泛型System.Collections.GenericList<T>, Dictionary<K,V>, HashSet<T>, Queue<T>型別安全、無裝箱、效能佳
並行System.Collections.ConcurrentConcurrentDictionary, ConcurrentQueue, BlockingCollection執行緒安全
不可變System.Collections.ImmutableImmutableList, ImmutableDictionary執行緒安全、函數式風格

介面導向選型

依操作需求選擇介面:

  • 僅需遍歷:`IEnumerable<T>`
  • 需索引存取:`IList<T>` / `IReadOnlyList<T>`
  • 鍵值查找:`IDictionary<K,V>` / `IReadOnlyDictionary<K,V>`
  • 集合運算:`ISet<T>`

公開 API 盡量回傳介面而非具體類別,保留實作彈性。

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