標籤:c#
理論:
C# 數組(Array) 數組是一個儲存相同類型元素的固定大小的循序集合。
數組是用來儲存資料的集合,通常認為數組是一個同一類型變數的集合。
聲明陣列變數並不是聲明 number0、number1、...、number99 一個個單獨的變數,而是聲明一個就像 numbers 這樣的變數,然後使用 numbers[0]、numbers[1]、...、numbers[99] 來表示一個個單獨的變數。
數組中某個指定的元素是通過索引來訪問的
所有的數組都是由連續的記憶體位置群組成的。最低的地址對應第一個元素,最高的地址對應最後一個元素。
650) this.width=650;" alt="C# 中的數組" src="http://outofmemory.cn/j/tutorial/wp-content/uploads/2014/04/arrays.jpg" />
聲明數組
在 C# 中聲明一個數組,您可以使用下面的文法:
datatype[] arrayName;
其中,
例如:
double[] balance;
賦值給數組
您可以通過使用索引號賦值給一個單獨的數組元素,比如:
double[] balance = new double[10];
balance[0] = 4500.0;
您可以在聲明數組的同時給數組賦值,比如:
double[] balance = { 2340.0, 4523.69, 3421.0};
您也可以建立並初始化一個數組,比如:
int [] marks = new int[5] { 99, 98, 92, 97, 95};
在上述情況下,你也可以省略數組的大小,比如:
int [] marks = new int[] { 99, 98, 92, 97, 95};
您也可以賦值一個陣列變數到另一個目標陣列變數中。在這種情況下,目標和源會指向相同的記憶體位置:
int [] marks = new int[] { 99, 98, 92, 97, 95};
int[] score = marks;
當您建立一個數組時,C# 編譯器會根據數群組類型隱式初始化每個數組元素為一個預設值。例如,int 數組的所有元素都會被初始化為 0。
訪問數組元素
元素是通過帶索引的數組名稱來訪問的。這是通過把元素的索引放置在數組名稱後的方括弧中來實現的。例如:
double salary = balance[9];
執行個體1:
下面是一個執行個體,使用上面提到的三個概念,即聲明、賦值、訪問數組:
using System;namespace ArrayApplication{ class MyArray { static void Main(string[] args) { //1.聲明數組 int [] n = new int[10]; /* n 是一個帶有 10 個整數的數組 */ int i,j; //2.賦值數組 /* 初始化數組 n 中的元素 */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } //3.訪問數組 /* 輸出每個數組元素的值 */ for (j = 0; j < 10; j++ ) { Console.WriteLine("Element[{0}] = {1}", j, n[j]); } Console.ReadKey(); } }}
當上面的代碼被編譯和執行時,它會產生下列結果:
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109
執行個體2:使用
foreach 迴圈
在前面的執行個體中,我們使用一個 for 迴圈來訪問每個數組元素。您也可以使用一個 foreach 語句來遍曆數組。
using System;namespace ArrayApplication{ class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n 是一個帶有 10 個整數的數組 */ /* 初始化數組 n 中的元素 */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* 輸出每個數組元素的值 */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); i++; } Console.ReadKey(); } }}
當上面的代碼被編譯和執行時,它會產生下列結果:
Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109
C# 數組細節
在 C# 中,數組是非常重要的,且需要瞭解更多的細節。下面列出了C# 程式員必須清楚的一些與數組相關的重要概念:
參考:
http://outofmemory.cn/csharp/tutorial/csharp-array.html
本文出自 “Ricky's Blog” 部落格,請務必保留此出處http://57388.blog.51cto.com/47388/1657416
56. C# -- 數組(Array)