C# 屬託管語言,記憶體由 GC 管理。但需呼叫作業系統 API、存取記憶體映射裝置或極致效能演算法時,可使用 unsafe 代碼直接操作指標。
unsafe 修飾符可用於:
class, struct, interface, delegatefield, method, property, event, indexer, operator, constructor, destructorunsafe { ... }僅在 unsafe 上下文有效(typeof 例外)。語法:unmanaged-type * 或 void *。
sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, boolenum 型別struct// C/C++: int *p1, *p2;
// C#:
int* p1, p2; // 兩個都是 int*,* 綁定在型別上
null(全 0 位),解引用行為未定義void*:未知型別指標,不可解引用/算術,但可互轉任意指標ref/out 傳遞,但易導致懸空指標| 運算子 | 用途 |
|---|---|
* | 間接存取(解引用) |
-> | 透過指標存取結構成員 |
[] | 指標索引存取 |
& | 取得變數位址 |
++ -- | 指標遞增/遞減 |
+ - | 指標算術運算 |
== != < > <= >= | 指標比較 |
stackalloc | 堆疊配置記憶體 |
fixed | 暫時固定變數位址 |