数组

您所在的位置:网站首页 二维数组说明 数组

数组

2023-04-21 15:25| 来源: 网络整理| 查看: 265

数组(C# 编程指南) 项目 04/07/2023

可以将同一类型的多个变量存储在一个数组数据结构中。 通过指定数组的元素类型来声明数组。 如果希望数组存储任意类型的元素,可将其类型指定为 object。 在 C# 的统一类型系统中,所有类型(预定义类型、用户定义类型、引用类型和值类型)都是直接或间接从 Object 继承的。

type[] arrayName; 示例

下面的示例创建一维数组、多维数组和交错数组:

class TestArraysClass { static void Main() { // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] { 1, 3, 5, 7, 9 }; // Alternative syntax. int[] array3 = { 1, 2, 3, 4, 5, 6 }; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } }; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] { 1, 2, 3, 4 }; } } 数组概述

数组具有以下属性:

数组可以是一维、多维或交错的。 创建数组实例时,将建立纬度数量和每个纬度的长度。 这些值在实例的生存期内无法更改。 数值数组元素的默认值设置为零,而引用元素设置为 null。 交错数组是数组的数组,因此其元素为引用类型且被初始化为 null。 数组从零开始编制索引:包含 n 元素的数组从 0 索引到 n-1。 数组元素可以是任何类型,其中包括数组类型。 数组类型是从抽象的基类型 Array 派生的引用类型。 所有数组都会实现 IList 和 IEnumerable。 可以使用 foreach 语句循环访问数组。 单维数组还实现了 IList 和 IEnumerable。 默认值行为 对于值类型,使用默认值(0 位模式)初始化数组元素;元素将具有值 0。 所有引用类型(包括不可为 null 的类型)都具有值 null。 对于可为 null 的类型,HasValue 设置为 false,元素将设置为 null。 作为对象的数组

在 C# 中,数组实际上是对象,而不只是如在 C 和 C++ 中的连续内存的可寻址区域。 Array 是所有数组类型的抽象基类型。 可以使用 Array 具有的属性和其他类成员。 例如,使用 Length 属性来获取数组的长度。 以下代码可将 numbers 数组的长度 5 分配给名为 lengthOfNumbers 的变量:

int[] numbers = { 1, 2, 3, 4, 5 }; int lengthOfNumbers = numbers.Length;

Array 类可提供多种其他有用的方法和属性,用于对数组进行排序、搜索和复制。 以下示例使用 Rank 属性显示数组的维数。

class TestArraysClass { static void Main() { // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has {0} dimensions.", theArray.Rank); } } // Output: The array has 2 dimensions. 另请参阅 如何使用一维数组 如何使用多维数组 如何使用交错数组 对数组使用 foreach 将数组作为参数传递 隐式类型的数组 C# 编程指南 集合

有关详细信息,请参阅 C# 语言规范。 该语言规范是 C# 语法和用法的权威资料。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3