C 陣列初始化簡析

2022-09-26 09:42:10 字數 2827 閱讀 9343

題外話:學習.net已經有一年了,從c#->asp.net->wpf。主要以看電子書為主,比較少寫**。現在回頭學習以前接觸過的,隨著知識與經驗的的積累。

總是有各種驚喜,震驚!c#陣列就是其中之一,我把它作為自己部落格園的**作。

c#陣列與其它c系列語言有著很多的不同,以前接觸的時候理解出現很大的偏差。尤其是對多維陣列的認識。多維陣列與c語言相比是乙個新概念。而最開始的

時候我把它當成交錯陣列的特殊型別。

首先重二維陣列與簡單的交錯陣列的初始化與訪問開始

複製** **如下:

int[,] nums=,

}; for (int i = nums.getlowerbound(0); i <= nums.getupperbound(0); i++) }

foreach (var num in nums)

//對任意維度的陣列,都可以這樣快速訪問,只是foreach不能修改變數。

而交錯陣列也能實現差不多的內容

複製** **如下:

int nums2 =,

new int

}; for (int i = nums2.getlowerbound(0); i <= nums2.getupperbound(0); i++) }

foreach (var ia in nums2) }

多維陣列儲存的資料可以用交錯陣列替代。交錯陣列是乙個有高維度的特殊陣列。而交錯陣列是陣列的陣列。而且陣列有乙個很重要的性質,

陣列裡面儲蓄的必須是相同的型別!這對理解各種複雜陣列是很重要的。

複雜的交錯陣列

複製** **如下:

bool cells31 = new bool[2]

, new bool

}, new bool[3]

, new bool ,

new bool

} };

我們必須這樣初始化 有一大堆new 因為交錯陣列是陣列的陣列,所以我們以前一直巢狀。但是需要很多的陣列型別,也可以建立無數的陣列型別。

複製** **如下:

console.writeline("交錯陣列型別");

console.writeline(cells31[0].gettype());

console.writeline(cells31[0][0].gettype());

console.writeline(cells31[0][0][0].gettype());

//交錯陣列型別

//這是交錯陣列裡面的型別。

// bool[2] 與boo[3] 是相同的型別,所以我們建立儲存結構不一致的陣列

接下來是最複雜的型別。將交錯陣列與多維陣列混合起來。如果能初始化下面的陣列那麼應該就理解的比較透徹了吧!

bool [,,][,,]foo;

我選擇乙個簡單點作為示例 bool [,]foo;

複製** **如下:

bool[,] foo = new bool[1][,]

, new bool[2]

}, ,

new bool[2]

} }

}; console.writeline("混合陣列型別");

console.writeline(foo.gettype());

console.writeline(foo[0].gettype());

console.writeline(foo[0][0,0].gettype());

console.writeline(foo[0][0, 0][0].gettype());

//結果 混合陣列型別

複製代kdsodtg碼 **如下:

//定義交錯陣列:一維陣列存放(二維int陣列存放(一維int陣列存放(四維int陣列)))

//標準的c#定義描述 array of( multi-array of( array of (nulti-array)))

int[,][, , ,] arr = new int[10][,][,,,];

//初始化 二維int陣列存放(一維int陣列存放(四維int陣列))

arr[4] = new int[1, 2][,,,];

//初始化 一維int陣列存放(四維int陣列)

arr[4][0, 1] =kdsodtg new int[3][, , ,];

//初始化 四維int陣列

arr[4][0, 1][2] = new int[1, 2, 3, 4];

console.writeline(arr.gettype());

console.writeline(arr[4].gettype());

console.writeline(arr[4][0, 1].gettype());

console.writeline(arr[4][0, 1][2].gettype());

//c#編譯器生成的名字與我們宣告的是倒著的。理解起來應該也沒差異吧

現在應該比較清晰了吧。我也不知道到底是不是每個程式設計師都理解這些,不過我是花了不少時間才明白的。

最後再考慮一下對陣列方法的影響。尤其是 clear();

複製** **如下:

console.writeline(foo[0][0,0][0]);

//輸出為flase

array.clear(foo,0,1);

console.writeline(foo[0][0, 0][0]);

//這裡會引發空引用異常。因為 bool[,]的型別的值已經變為null。

本文標題: c#陣列初始化簡析

本文位址:

linux memblock 初始化簡介

setup machine fdt fdt pointer early init dt scan early init dt scan nodes 從dts中獲取 記憶體容量,位址資訊 setup memory,calling early init dt add memory arch of sca...

sysfs之platform匯流排初始化簡單分析

int init platform bus init void 第5行使用device register函式註冊platform bus裝置 第8行使用bus register函式註冊乙個匯流排。第10行如果註冊失敗,解除安裝匯流排。int device register struct device...

字典排序,初始化,簡單使用

如 想對字典wordhash排序 通過list實現 wordlist wordhash wordlist ufeff 1 calvin 1 shi 1 鏈結 1 www 1 zhihu 1 question 1 27068465 1 item item 1 代表是元組 calvin 1 中的第二個元...