13.3 数组是对象
数组实例是从System.Array
继承类型的对象。由于数组从BCL
基类派生而来,它们也继承了BCL
基类中很多有用的成员。如Rank
,Length
等等。
数组可以分为值类型数组和引用类型数组。
13.4 一维数组和矩形数组
int[] arrayA; // 一维数组,注意括号位置
int[,] arrayB; // 二维数组,逗号是秩说明符
long[,,] arrayC; // 三位数组,注意不能在声明中放长度
13.5 实例化一维数组或矩形数组
int[,,] arrayA = new int[2,3,6];
MyClass[] arrayB = new Myclass[5];
13.7 初始化数组
int[] arrayA = new int[5] { 1, 2, 3, 4, 5};
int[,] arrayB = new int[2, 3] { { 1, 2, 3 }, { 2, 3, 4 } };
int[,] arrayQuick = { { 1, 2, 3 }, { 2, 3, 4 } }; // 快捷语法
var arrayImplicit = new[,] { { 1, 2, 3 }, { 2, 3, 4 } }; // 隐式类型数组
13.8 交错数组
int[][] array2D; // 每个维度有一对独立的方括号
int[][][] array3D;
int[][][] array3D = new int[2][][]; // 快捷实例化,注意只能初始化顶层数组
实例化完整的交错数组需要:
- 实例化顶层数组;
- 分别实例化每一个子数组,把新建数组的引用赋给它们所属数组的合适元素。
// 实例化完整的交错数组
int[][] array2D = new int[2][];
array2D[0] = new int[] { 1, 2, 3 };
array2D[1] = new int[] { 4, 5, 6 };
13.10 foreach
语句
int[][] array2D = new int[2][];
array2D[0] = new int[] { 1, 2, 3 };
array2D[1] = new int[] { 4, 5, 6, 7 };
foreach (var arr in array2D)
{
Console.WriteLine("Starting new array:");
foreach (var i in arr)
Console.Write("{0} ", i);
Console.WriteLine("");
}
13.11 数组协变
符合下面的情况就可以使用数组协变:
- 数组是引用类型数组;
- 赋值的对象类型和数组基类型之间有隐式转换或显示转换。
13.12 数组继承的有用成员
详见 P251.
13.14 数组与ref
返回和ref
局部变量
// 找到数组中第一个非零元素并返回其引用,若找不到则 found 为 false
public static ref int PointerToFirstNoneZero(int[] nums, out bool found)
{
for (int i = 0; i < nums.Length; ++i)
if (nums[i] != 0)
{
found = true;
return ref nums[i];
}
found = false;
return ref nums[0];
}
static void Main()
{
int[] arr = { 0, 0, 0, 1, 2, 3 };
Console.WriteLine("Before:");
for (int i = 0; i < arr.Length; ++i)
Console.Write("{0} ", arr[i]);
Console.WriteLine("");
ref int pointer = ref PointerToFirstNoneZero(arr, out bool flag);
if (flag)
pointer = 0;
Console.WriteLine("After:");
for (int i = 0; i < arr.Length; ++i)
Console.Write("{0} ", arr[i]);
Console.WriteLine("");
}
以上代码输出如下:
Before:
0 0 0 1 2 3
After:
0 0 0 0 2 3