C#基礎(chǔ)語(yǔ)法:as 運(yùn)算符使用實(shí)例
as 運(yùn)算符類似于強(qiáng)制轉(zhuǎn)換操作。但是,如果無(wú)法進(jìn)行轉(zhuǎn)換,則 as 返回 null 而非引發(fā)異常。
as 運(yùn)算符只執(zhí)行引用轉(zhuǎn)換和裝箱轉(zhuǎn)換。as 運(yùn)算符無(wú)法執(zhí)行其他轉(zhuǎn)換,如用戶定義的轉(zhuǎn)換,這類轉(zhuǎn)換應(yīng)使用強(qiáng)制轉(zhuǎn)換表達(dá)式來(lái)執(zhí)行。
expression as type
等效于(但只計(jì)算一次 expression)
expression is type ? (type)expression : (type)null
as 運(yùn)算符用于在兼容的引用類型之間執(zhí)行轉(zhuǎn)換。例如:
// 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 string 1:not a string 2:'hello' 3:not a string 4:not a string 5:not a string
相關(guān)文章
C#調(diào)用C++動(dòng)態(tài)庫(kù)接口函數(shù)和回調(diào)函數(shù)方法
這篇文章主要介紹了C#調(diào)用C++動(dòng)態(tài)庫(kù)接口函數(shù)和回調(diào)函數(shù)方法,通過(guò)C++端編寫接口展開內(nèi)容,文章介紹詳細(xì)具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-03-03C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能
這篇文章主要為大家詳細(xì)介紹了C#使用NPOI實(shí)現(xiàn)Excel導(dǎo)入導(dǎo)出功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02