溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

C#中怎么聲明數組

發布時間:2021-07-07 17:38:05 來源:億速云 閱讀:692 作者:Leah 欄目:編程語言

今天就跟大家聊聊有關C#中怎么聲明數組,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。

C#聲明數組時,方括號([])必須跟在類型后面,而不是標識符后面。在C#中,將方括號放在標識符后是不合法的語法。

int[] table; // not int table[];

另一細節是,數組的大小不是其類型的一部分,而在 C 語言中它卻是數組類型的一部分。這使您可以聲明一個數組并向它分配 int 對象的任意數組,而不管數組長度如何。

int[] numbers; // declare numbers as an int array of any size   numbers = new int[10];  // numbers is a 10-element array   numbers = new int[20];  // now it's a 20-element array

C#聲明數組細節討論:

C# 支持一維數組、多維數組(矩形數組)和數組的數組(交錯的數組)。下面的示例展示如何聲明不同類型的數組:

C#聲明數組之一維數組:

int[] numbers;

C#聲明數組之多維數組:

string[,] names;

C#聲明數組之數組的數組(交錯的):

byte[][] scores;

C#聲明數組之(如上所示)并不實際創建它們。在 C# 中,數組是對象(本教程稍后討論),必須進行實例化。下面的示例展示如何創建數組:

C#聲明數組之實例化一維數組:

int[] numbers = new int[5];

C#聲明數組之實例化多維數組:

string[,] names = new string[5,4];

C#聲明數組之實例化數組的數組(交錯的):

byte[][] scores = new byte[5][];   for (int x = 0; x < scores.Length; x++)    {   scores[x] = new byte[4];   }

C#聲明數組之實例化三維的矩形數組:

int[,,] buttons = new int[4,5,3];

甚至可以將矩形數組和交錯數組混合使用。例如,下面的代碼聲明了類型為 int 的二維數組的三維數組的一維數組。

int[][,,][,] numbers;

C#聲明數組之實例化示例

//下面是一個完整的 C# 程序,它聲明并實例化上面所討論的數組。   // arrays.cs   using System;   class DeclareArraysSample  {  public static void Main()  {  // Single-dimensional array  int[] numbers = new int[5];  // Multidimensional array  string[,] names = new string[5,4];  // Array-of-arrays (jagged array)  byte[][] scores = new byte[5][];  // Create the jagged array   for (int i = 0; i < scores.Length; i++)  {  scores[i] = new byte[i+3];  }  // Print length of each row   for (int i = 0; i < scores.Length; i++)   {  Console.WriteLine(  "Length of row {0} is {1}", i, scores[i].Length);  }  }  }

C#聲明數組之實例化示例輸出

Length of row 0 is 3   Length of row 1 is 4   Length of row 2 is 5   Length of row 3 is 6   Length of row 4 is 7

看完上述內容,你們對C#中怎么聲明數組有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女