as 運算符:用於在兼容的引用類型之間執行轉換。
說明:
1>:as操作符類似於強制轉換,但又有區別,當對象為null時,不會拋異常而是會返回null。
object _object = null;
student _s = _object as student;
_object as student其實相當於_object is student?(student)_object:null;之所以這樣說,我們可 以從兩者的IL代碼中看出些結論:首先我們實例化個基類對象。
object o = new student();
然後分別執行:
1):o is student,對應IL代碼
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代碼大小 18 (0x12)
.maxstack 2
.locals init ([0] object o,
[1] bool isstudent2)
IL_0000: nop
IL_0001: newobj instance void JmTest.ConsoleApplication1.student::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: isinst JmTest.ConsoleApplication1.student
IL_000d: ldnull
IL_000e: cgt.un
IL_0010: stloc.1
IL_0011: ret
} // end of method Program::Main
2):o as student,對應IL代碼
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// 代碼大小 15 (0xf)
.maxstack 1
.locals init ([0] object o,
[1] class JmTest.ConsoleApplication1.student s2)
IL_0000: nop
IL_0001: newobj instance void JmTest.ConsoleApplication1.student::.ctor()
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: isinst JmTest.ConsoleApplication1.student
IL_000d: stloc.1
IL_000e: ret
} // end of method Program::Main
小結:兩段IL代碼都執行了isinst,它代表的意思是:測試對象引用是否為特定類的實例,在as操作符 後面有一個stloc.1它代表的意思是:從計算堆棧的頂部彈出當前值到索引1處的局部變量列表中。從這兩 條IL語句的用途可以說明is和as操作符的部分關系。
2>:as 運算符只執行引用轉換和裝箱轉換,無法執行其他轉換。下面的代碼是錯誤的:
object _object = null;
//試圖將一個對象轉換成委托
student _s = _object as student;
testdelegate test = _s as testdelegate;