as 運算子 執行參考轉換或裝箱轉換,失敗時回傳 null而不拋例外。語法:expr as Type,Type 必須為參考型別(類別、介面、委派、陣列、object)。
Type。expr as Type 等價:expr is Type ? (Type)expr : (Type)null(但只檢查一次)。
string s = 'a' as string; // 編譯警告 CS0458:char 永不為 string
// 結果:s = null,程式繼續執行
object obj = "hello";
string str = obj as string; // str = "hello"
int? num = obj as int?; // 編譯錯誤:int? 為實值型別
| as | (T)expr | |
|---|---|---|
| 失敗行為 | 回傳 null | 拋 InvalidCastException |
| 適用型別 | 僅參考型別 | 任意型別 |
| 拆箱支援 | ❌ | ✅ |
| 使用者定義轉換 | ❌ | ✅ |
as + null 檢查。is T v 型別模式,語意更清晰。