今天就跟大家聊聊有關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#中怎么聲明數組有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。