C#聲明數(shù)組的詳細解析
C#聲明數(shù)組的操作是什么呢?C#聲明數(shù)組的作用是什么呢?下面我們一一探討,C#數(shù)組從零開始建立索引,即數(shù)組索引從零開始。C#中數(shù)組的工作方式與在大多數(shù)其他流行語言中的工作方式類似。但還有一些差異應(yīng)引起注意。
C#聲明數(shù)組時,方括號([])必須跟在類型后面,而不是標(biāo)識符后面。在C#中,將方括號放在標(biāo)識符后是不合法的語法。
- int[] table; // not int table[];
另一細節(jié)是,數(shù)組的大小不是其類型的一部分,而在 C 語言中它卻是數(shù)組類型的一部分。這使您可以聲明一個數(shù)組并向它分配 int 對象的任意數(shù)組,而不管數(shù)組長度如何。
- 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#聲明數(shù)組細節(jié)討論:
C# 支持一維數(shù)組、多維數(shù)組(矩形數(shù)組)和數(shù)組的數(shù)組(交錯的數(shù)組)。下面的示例展示如何聲明不同類型的數(shù)組:
C#聲明數(shù)組之一維數(shù)組:
- int[] numbers;
C#聲明數(shù)組之多維數(shù)組:
- string[,] names;
C#聲明數(shù)組之?dāng)?shù)組的數(shù)組(交錯的):
- byte[][] scores;
C#聲明數(shù)組之(如上所示)并不實際創(chuàng)建它們。在 C# 中,數(shù)組是對象(本教程稍后討論),必須進行實例化。下面的示例展示如何創(chuàng)建數(shù)組:
C#聲明數(shù)組之實例化一維數(shù)組:
- int[] numbers = new int[5];
C#聲明數(shù)組之實例化多維數(shù)組:
- string[,] names = new string[5,4];
C#聲明數(shù)組之實例化數(shù)組的數(shù)組(交錯的):
- byte[][] scores = new byte[5][];
- for (int x = 0; x < scores.Length; x++)
- {
- scores[x] = new byte[4];
- }
C#聲明數(shù)組之實例化三維的矩形數(shù)組:
- int[,,] buttons = new int[4,5,3];
甚至可以將矩形數(shù)組和交錯數(shù)組混合使用。例如,下面的代碼聲明了類型為 int 的二維數(shù)組的三維數(shù)組的一維數(shù)組。
- int[][,,][,] numbers;
C#聲明數(shù)組之實例化示例
- //下面是一個完整的 C# 程序,它聲明并實例化上面所討論的數(shù)組。
- // 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#聲明數(shù)組之實例化示例輸出
- 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#聲明數(shù)組及實例化相關(guān)的內(nèi)容就向你介紹到這里,希望對你了解和學(xué)習(xí)C#聲明數(shù)組及相關(guān)內(nèi)容有所幫助。
【編輯推薦】