C#聲明數組的詳細解析
C#聲明數組的操作是什么呢?C#聲明數組的作用是什么呢?下面我們一一探討,C#數組從零開始建立索引,即數組索引從零開始。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#聲明數組及實例化相關的內容就向你介紹到這里,希望對你了解和學習C#聲明數組及相關內容有所幫助。
【編輯推薦】