W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
object
或 System.Object
是所有類型的最終基類。
任何類型都可以u(píng)pcast到對(duì)象。
以下代碼創(chuàng)建一個(gè)類Stack以提供First-In-Last_Out數(shù)據(jù)結(jié)構(gòu)。
public class Stack { int position; object[] data = new object[10]; public void Push (object obj) { data[position++] = obj; } public object Pop() { return data[--position]; } }
因?yàn)镾tack使用對(duì)象類型,我們可以推送和彈出任何類型到和從堆棧。
Stack stack = new Stack(); stack.Push ("CSS"); string s = (string) stack.Pop(); // Downcast, so explicit cast is needed Console.WriteLine (s);
在值類型和對(duì)象之間進(jìn)行轉(zhuǎn)換時(shí),CLR必須執(zhí)行裝箱和取消裝箱的過程。
裝箱是將值類型實(shí)例轉(zhuǎn)換為引用類型實(shí)例。
引用類型可以是對(duì)象類或接口。
int x = 1; object obj = x; // Box the int
拆裝箱會(huì)將操作轉(zhuǎn)換為原始值類型,從而反轉(zhuǎn)操作:
int y = (int)obj; // Unbox the int
拆箱需要顯式強(qiáng)制轉(zhuǎn)換。
例如,以下引發(fā)異常,因?yàn)閘ong不完全匹配int:
object obj = 1; // 1 is inferred to be of type int long x = (long) obj; // InvalidCastException
以下代碼執(zhí)行取消裝箱和強(qiáng)制轉(zhuǎn)換:
object obj = 9; long x = (int) obj;
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: