C# 中的数组是什么?

csharpprogrammingserver side programming更新于 2025/10/15 2:37:17

数组存储的是固定大小且连续的同类型元素集合。数组通常用于存储数据集合,但通常将数组视为存储在连续内存位置的同类型变量集合更为实用。

要在 C# 中声明数组,可以使用以下语法 −

datatype[] arrayName;

其中,

  • datatype 用于指定数组中元素的类型。
  • [ ] 指定数组的秩。秩指定数组的大小。
  • arrayName 指定数组的名称。

现在让我们看看如何在 C# 中实现数组 −

示例

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
          int [] n = new int[10]; /* n 是一个包含 10 个整数的数组 */
         int i,j;
         /* 初始化数组 n 的元素 */
         for ( i = 0; i < 10; i++ ) {
            n[ i ] = i + 100;
         }

         /* 输出每个数组元素的值 */
         for (j = 0; j < 10; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
         Console.ReadKey();
      }
   }
}

输出

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

相关文章