C# 图解教程 第 13 章 数组(笔记+模仿代码)

13.3 数组是对象

数组实例是从System.Array继承类型的对象。由于数组从BCL基类派生而来,它们也继承了BCL基类中很多有用的成员。如RankLength等等。

数组可以分为值类型数组和引用类型数组。

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][][];	// 快捷实例化,注意只能初始化顶层数组

实例化完整的交错数组需要:

  1. 实例化顶层数组;
  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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值