淺談C#數(shù)組工作方式
C#數(shù)組工作方式概述
C#數(shù)組從零開始建立索引,即數(shù)組索引從零開始。C#數(shù)組工作方式與在大多數(shù)其他流行語言中的工作方式類似。但還有一些差異應(yīng)引起注意。
聲明數(shù)組時(shí),方括號(hào) ([]) 必須跟在類型后面,而不是標(biāo)識(shí)符后面。在 C# 中,將方括號(hào)放在標(biāo)識(shí)符后是不合法的語法。
int[] table; // not int table[];
另一細(xì)節(jié)是,數(shù)組的大小不是其類型的一部分,而在 C 語言中它卻是數(shù)組類型的一部分。這使您可以聲明一個(gè)數(shù)組并向它分配 int 對(duì)象的任意數(shù)組,而不管數(shù)組長(zhǎng)度如何。
- 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
聲明數(shù)組
C# 支持一維數(shù)組、多維數(shù)組(矩形數(shù)組)和數(shù)組的數(shù)組(交錯(cuò)的數(shù)組)。下面的示例展示如何聲明不同類型的數(shù)組:
◆一維數(shù)組:int[] numbers;
◆多維數(shù)組:string[,] names;
◆數(shù)組的數(shù)組(交錯(cuò)的):byte[][] scores;
聲明數(shù)組(如上所示)并不實(shí)際創(chuàng)建它們。在 C# 中,數(shù)組是對(duì)象(本教程稍后討論),必須進(jìn)行實(shí)例化。下面的示例展示如何創(chuàng)建數(shù)組:
◆一維數(shù)組:int[] numbers = new int[5];
◆多維數(shù)組:string[,] names = new string[5,4];
◆數(shù)組的數(shù)組(交錯(cuò)的):
- byte[][] scores = new byte[5][];
- for (int x = 0; x < scores.Length; x++)
- {
- scores[x] = new byte[4];
- }
還可以有更大的數(shù)組。例如,可以有三維的矩形數(shù)組:int[,,] buttons = new int[4,5,3];
甚至可以將矩形數(shù)組和交錯(cuò)數(shù)組混合使用。例如,下面的代碼聲明了類型為 int 的二維數(shù)組的三維數(shù)組的一維數(shù)組。int[][,,][,] numbers;以上介紹C#數(shù)組工作方式
【編輯推薦】