循環輸郵索引值,使用for是沒有任何問題:

class Bh { public string[] str { get; set; } public void TestFor() { for (int i = 0; i < str.Length; i++) { Console.WriteLine("index:{0},Value:{1}", i, str[i]); } } }
運行程序:
但是,某一情況之下,你在程序中,是使用foreach方法進行循環的,但又想輸出索引的話,那怎樣實現呢?

class Bh { public string[] str { get; set; } public void TestFor() { for (int i = 0; i < str.Length; i++) { Console.WriteLine("index:{0},Value:{1}", i, str[i]); } } public void TestForeach() { int idx = 0; foreach (string s in str) { Console.WriteLine("index:{0},Value:{1}", idx, s); idx++; } } }