Skip to content

ZH TW CSharp Collections

Bad Newbie edited this page Oct 16, 2026 · 3 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

列表、字典、HashSet、佇列和堆疊

手冊C# · 範例UO

透過操作選擇集合:List<T>儲存有序的可變列表,Dictionary<TKey,TValue> - 按鍵的值,HashSet<T> - 唯一值,Queue<T> - 順序FIFO,Stack<T> - LIFO。通用參數指定元素類型。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
var counts = new System.Collections.Generic.List<int> { 2, 3 };
counts.Add(4);
System.Console.WriteLine(counts.Count);

結果:

3
var visited = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
visited.Add("backpack");
visited.Add("BACKPACK");
UO.Print($"Unique names: {visited.Count}");
var delays = new Dictionary<string, int>
{
    ["short"] = 100,
    ["long"] = 500
};
if (delays.TryGetValue("short", out int delay))
{
    await WaitAsync(delay);
}
var queue = new Queue<string>();
queue.Enqueue("first");
queue.Enqueue("second");
UO.Print(queue.Dequeue());

如果沒有合適的演算法,請勿在 foreach 期間修改常規集合。對於線程的同時操作,有單獨的並發集合;它們本身並不使遊戲操作線程安全。

官方文件:列表、字典、HashSet、佇列和堆疊 - Microsoft Learn。

Clone this wiki locally