【C#】數組_訪問數組元素(20)


通過索引訪問
•可以通過數組的索引(位置的序號)進行讀寫操作。
•語法:
數組名[索引]
•例如:
string[] array = new string[] {"a", "b", "c"};
Console.WriteLine(array[0]);--獲取數組第一個元素
Console.WriteLine(array[2]);--獲取數組第三個元素

 

通過for 遍歷
•遍歷:按照某種順序訪問每一個元素。
•for 循環遍歷數組元素,正序輸出到控制台中:
string[] array=newstring[] { "a", "b", "c"};
for(inti=0; i<array.Length; i++)
{
Console.WriteLine( array[i] );
}
 
 
通過for 遍歷(續1)
•for 循環遍歷數組元素,倒序輸出到控制台中:
string[] array=newstring[] { "a", "b", "c"};
for(inti=array.Length -1; i>= 0; i--)
{
Console.WriteLine( array[i] );
}
 
 
通過foreach遍歷
•foreach是一種更簡單更明了的讀取數組元素的語句。
•局限性:
--只能讀取全部元素(語句本身)
--不能修改元素
--只能遍歷實現Ienumerable接口的集合對象
•語法:
foreach(元素類型變量名in 數組名)
{
變量名表示數組中的每個元素
}

 

•foreach循環遍歷數組元素,輸出到控制台中:
string[] array=newstring[] { "a", "b", "c"};
foreach(stringiteminarray)
{
Console.WriteLine( item );
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM