C# 提供自動記憶體管理,開發人員無須手動分配與釋放記憶體區塊。這不僅減輕負擔,在大多數情況下還能提升程式碼品質與開發效率,且不犧牲表達能力或效能。
以下堆疊實作展示節點物件在不再被參考時自動成為回收目標:
public class Stack {
private Node first = null;
public bool Empty => first == null;
public object Pop() {
if (first == null) throw new Exception("堆疊為空");
object temp = first.Value;
first = first.Next;
return temp;
}
public void Push(object o) {
first = new Node(o, first);
}
private class Node {
public Node Next;
public object Value;
public Node(object value) : this(value, null) {}
public Node(object value, Node next) { Next = next; Value = value; }
}
}
當執行 s = null; 後,Stack 及其 10 個 Node 實例皆符合回收條件。回收器可能立即清理,但不保證即時性。
對於需要精確控制或效能微調的場景,C# 提供 unsafe 區塊,允許直接操作指標與物件位址。需使用 fixed 陳述式暫時固定物件,防止回收器移動:
static void WriteLocations(byte[] arr) {
unsafe {
fixed (byte* pArray = arr) {
byte* pElem = pArray;
for (int i = 0; i < arr.Length; i++) {
byte value = *pElem;
Console.WriteLine("arr[{0}] at 0x{1:X} is {2}", i, (uint)pElem, value);
pElem++;
}
}
}
}
安全性設計: unsafe 代碼必須明確標記,編譯器與執行引擎確保其無法偽裝為安全代碼,僅限受信任環境使用。