C#系列 --4 array中的Rectangular arrays 和Jagged arrays
阿新 • • 發佈:2018-11-11
陣列 Arrays
char [] vowels = new char[5]
和C++的 new 動態申請記憶體一樣。。。
- for 迴圈遍歷
for (int i = 0; i < vowels.Length; i++) Console.Write (vowels[i]);
陣列的Length屬性返回陣列中的元素個數也就是陣列的長度,陣列一旦被建立,長度(length)不可改變。System.Collection
中提供了長度可變的陣列和字典等更高階的資料結構
-
陣列初始化:
char[] vowels = new char[] {'a','e','i','o','u'};
char[] vowels = {'a','e','i','o','u'};
所有的陣列都繼承於System.Array
類,
預設的元素初始化
建立陣列時,總是先使用預設值初始化,預設值是在記憶體中按位元位清0後的值。比如,建立一個整型陣列,int
是值型別,將會在一塊連續的記憶體中建立1000個整數,每個元素的值為0
int[] a = new int[1000];
Console.Write (a[123]); // 0
值型別和引用型別
當陣列的元素型別是值型別還是引用型別對效能有重要的影響
- 值型別: 每個元素都將直接分配一個記憶體值
public struct Point { public int X, Y; } ... Point[] a = new Point[1000]; int x = a[500].X; // 0
- 引用型別:每個元素分配一個null的引用,和C++一樣,使用前要先完成初始化,否則出現
NullReferenceException
的錯誤
public class Point { public int X, Y; }
...
Point[] a = new Point[1000];
int x = a[500].X; // Runtime error, NullReferenceException
使用前先完成初始化:
Point[] a = new Point[1000]; for (int i = 0; i < a.Length; i++) // Iterate i from 0 to 999 a[i] = new Point(); // Set array element i with new point
多維陣列 multidimensional arrays
分為rectangular and jagged(矩形陣列和鋸齒狀的),
- Rectangular arrays:代表的是n維的記憶體塊
- jagged arrays: 陣列的陣列
Rectangular arrays
在定義時使用逗號,將每一維度分開
GetLength(dim)方法得到指定維度上的長度
int[,] matrix = new int[3,3];
for (int i = 0; i < matrix.GetLength(0); i++)
for (int j = 0; j < matrix.GetLength(1); j++)
matrix[i,j] = i * 3 + j;
int[,] matrix = new int[,]
{
{0,1,2},
{3,4,5},
{6,7,8}
};
Jagged arrays
使用連續的方括號代表每一個維度, 這種方式在c++中你們應該學過的
例子: 建立一個二維鋸齒陣列,最外側維度的長度是3
int[][] matrix = new int[3][];
初始化:
for (int i = 0; i < matrix.Length; i++)
{
matrix[i] = new int[3]; // Create inner array
for (int j = 0; j < matrix[i].Length; j++)
matrix[i][j] = i * 3 + j;
}
int[][] matrix = new int[][]
{
new int[] {0,1,2},
new int[] {3,4,5},
new int[] {6,7,8,9}
};
// 兩者混合
int[][,] jaggedArray4 = new int[3][,]
{
new int[,] { {1,3}, {5,7} },
new int[,] { {0,2}, {4,6}, {8,10} },
new int[,] { {11,22}, {99,88}, {0,9} }
};
利用c++指標的觀點理解jagged陣列,用c++中普通的二維陣列理解Rectangular陣列
可以使用var型別初始化,型別交給編譯器去推斷。
var i = 3; // i is implicitly of type int
var s = "sausage"; // s is implicitly of type string
// Therefore:
var rectMatrix = new int[,] // rectMatrix is implicitly of type int[,]
{
{0,1,2},
{3,4,5},
{6,7,8}
};
var jaggedMat = new int[][] // jaggedMat is implicitly of type int[][]
{
new int[] {0,1,2},
new int[] {3,4,5},
new int[] {6,7,8}
};
//更隱式的型別轉換
var x = new[] {1,10000000000}; // all convertible to long
Bounds Checking 便捷檢查
所有的陣列索引都會進行邊界檢查,無效的索引會丟擲IndexOutOfRangeException
異常錯誤
int[] arr = new int[3];
arr[3] = 1; // IndexOutOfRangeException thrown