as 運算符類似于強制轉換操作。但是,如果無法進行轉換,則 as 返回 null 而非引發異常。
as 運算符只執行引用轉換和裝箱轉換。as 運算符無法執行其他轉換,如用戶定義的轉換,這類轉換應使用強制轉換表達式來執行。
expression as type
等效于(但只計算一次 expression)
expression is type ? (type)expression : (type)null
as 運算符用于在兼容的引用類型之間執行轉換。例如:
// cs_keyword_as.cs// The as operator.using System;class Class1{}class Class2{}class MainClass{ static void Main() { object[] objArray = new object[6]; objArray[0] = new Class1(); objArray[1] = new Class2(); objArray[2] = "hello"; objArray[3] = 123; objArray[4] = 123.4; objArray[5] = null; for (int i = 0; i < objArray.Length; ++i) { string s = objArray[i] as string; Console.Write("{0}:", i); if (s != null) { Console.WriteLine("'" + s + "'"); } else { Console.WriteLine("not a string"); } } }}//=============================================================// 0:not a string1:not a string2:'hello'3:not a string4:not a string5:not a string
新聞熱點
疑難解答