位置:首頁 > 軟件操作教程 > 編程開發(fā) > C# > 問題詳情

C# foreach 循環(huán)

提問人:劉團(tuán)圓發(fā)布時(shí)間:2020-12-04

foreach循環(huán)可以使用一種簡便的語法來定位數(shù)組中的每個(gè)元素:

foreach (<baseType> <name> in <array>)

{

    // can use <name> for each element

}

這個(gè)循環(huán)會(huì)迭代每個(gè)元素,依次把每個(gè)元素放在變量中,且不存在訪問非法元素的危險(xiǎn)。不需要考慮數(shù)組中有多少個(gè)元素,并可以確保將在循環(huán)中使用每個(gè)元素。使用這個(gè)循環(huán),可以修改上個(gè)示例中的代碼,如下所示:

static void Main(string[] args)

{

    string [] friendNames = ( "Todd Anthony", "Kevin Holton","Shane Laigle" };

    WriteLine($"Here are {friendNames.Length} of my friends:"); 

    foreach (string friendMame in friendNames)

    {

      WriteLine(friendName);

    }

    ReadKey();

}

這段代碼的輸出結(jié)果與前面的“試一試”示例完全相同。使用這種方法和標(biāo)準(zhǔn)的for循環(huán)的主要區(qū)別在于:foreach循環(huán)對數(shù)組內(nèi)容進(jìn)行只讀訪問,所以不能改變?nèi)魏卧氐闹怠@?,不能編寫如下代碼:

foreach (string friendName in friendNames) 

{

    friendName = "Rupert the bear";

}

如果編譯這段代碼,就會(huì)失敗。但如果使用簡單的for循環(huán),就可以給數(shù)組元素賦值。

繼續(xù)查找其他問題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部