as 用於兼容引用類型之間的轉換,類似強制轉換但更安全:轉換失敗不拋異常,直接返回 null。
object _object = null;
Student _s = _object as Student; // _s 為 null,不拋出異常
其邏輯等價於:_object is Student ? (Student)_object : null。
以 object o = new Student(); 為例:
IL_0007: ldloc.0
IL_0008: isinst JmTest.ConsoleApplication1.Student
IL_000d: ldnull
IL_000e: cgt.un
IL_0010: stloc.1
isinst 檢查類型,若為目標類型則返回對象引用否則 null;cgt.un 比較結果是否大於 null,最終存入 bool 變量。
IL_0007: ldloc.0
IL_0008: isinst JmTest.ConsoleApplication1.Student
IL_000d: stloc.1
同樣執行 isinst,但直接將結果(對象引用或 null)存入目標變量,省去了比較與分支跳轉。
isinst 指令進行類型檢查。is 產生 bool 結果,適合「判斷後再轉換」場景;as 直接產生轉換後引用,適合「嘗試轉換並處理 null」場景。as 僅支援引用轉換、裝箱轉換,不支援使用者定義轉換、拆箱轉換、委托轉換等。object _object = null;
Student _s = _object as Student;
TestDelegate test = _s as TestDelegate; // 編譯錯誤:as 不能用於委托轉換