数组(C# 编程指南)Arrays (C# Programming Guide)

可以将同一类型的多个变量存储在一个数组数据结构中。You can store multiple variables of the same type in an array data structure. 通过指定数组的元素类型来声明数组。You declare an array by specifying the type of its elements. 如果希望数组存储任意类型的元素,可将其类型指定为 objectIf you want the array to store elements of any type, you can specify object as its type. 在 C# 的统一类型系统中,所有类型(预定义类型、用户定义类型、引用类型和值类型)都是直接或间接从 Object 继承的。In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

type[] arrayName;

示例Example

下面的示例创建一维数组、多维数组和交错数组:The following example creates single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass
{
    static void Main()
    {
        // Declare a single-dimensional array. 
        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 };
    }
}

数组概述Array overview

数组具有以下属性:An array has the following properties:

  • 数组可以是一维多维交错的。An array can be Single-Dimensional, Multidimensional or Jagged.
  • 创建数组实例时,将建立纬度数量和每个纬度的长度。The number of dimensions and the length of each dimension are established when the array instance is created. 这些值在实例的生存期内无法更改。These values can't be changed during the lifetime of the instance.
  • 数值数组元素的默认值设置为零,而引用元素设置为 null。The default values of numeric array elements are set to zero, and reference elements are set to null.
  • 交错数组是数组的数组,因此其元素为引用类型且被初始化为 nullA jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null.
  • 数组从零开始编制索引:包含 n 元素的数组从 0 索引到 n-1Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
  • 数组元素可以是任何类型,其中包括数组类型。Array elements can be of any type, including an array type.
  • 数组类型是从抽象的基类型 Array 派生的引用类型Array types are reference types derived from the abstract base type Array. 由于此类型实现 IEnumerableIEnumerable<T>,因此可以在 C# 中的所有数组上使用 foreach 迭代。Since this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration on all arrays in C#.

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See also