C#基礎語法:as 運算符使用實例
更新時間:2015年06月18日 10:08:47 投稿:junjie
這篇文章主要介紹了C#基礎語法:as 運算符使用實例,本文給出了類、字符串、數(shù)字、浮點數(shù)、null等值的運算實例,需要的朋友可以參考下
as 運算符類似于強制轉換操作。但是,如果無法進行轉換,則 as 返回 null 而非引發(fā)異常。
as 運算符只執(zhí)行引用轉換和裝箱轉換。as 運算符無法執(zhí)行其他轉換,如用戶定義的轉換,這類轉換應使用強制轉換表達式來執(zhí)行。
expression as type
等效于(但只計算一次 expression)
expression is type ? (type)expression : (type)null
as 運算符用于在兼容的引用類型之間執(zhí)行轉換。例如:
// 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
相關文章
C#調用C++動態(tài)庫接口函數(shù)和回調函數(shù)方法
這篇文章主要介紹了C#調用C++動態(tài)庫接口函數(shù)和回調函數(shù)方法,通過C++端編寫接口展開內容,文章介紹詳細具有一定的參考價值,需要的小伙伴可以參考一下2022-03-03