在 C# 中宣告一個數組會建立一個數組嗎?


宣告一個數組並不會在記憶體中初始化該陣列。當初始化了陣列變數時,可以給該陣列賦值。

以下是宣告且不會建立陣列的內容 −

int[] id;

以下建立了一個整數陣列。該陣列是一個引用型別,所以需要使用 new 關鍵字來建立該陣列的一個例項 −

Int[] id = new int[5] {};

我們來看一個示例 −

示例

 線上演示

using System;

namespace ArrayApplication {
   public class MyArray {
      public static void Main(string[] args) {
         int [] n = new int[5];
         int i,j;
     
         /* initialize elements of array n */
         for ( i = 0; i < 5; i++ ) {
            n[ i ] = i + 10;
         }

         /* output each array element's value */
         for (j = 0; j < 5; j++ ) {
            Console.WriteLine("Element[{0}] = {1}", j, n[j]);
         }
      }
   }
}

輸出

Element[0] = 10
Element[1] = 11
Element[2] = 12
Element[3] = 13
Element[4] = 14

更新於: 22-6 月 -2020

62 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.