Foreach循环输出索引值

时间:2023-11-13 19:02:26

循环输邮索引值,使用for是没有任何问题:

Foreach循环输出索引值

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

Source Code

运行程序:

Foreach循环输出索引值

但是,某一情况之下,你在程序中,是使用foreach方法进行循环的,但又想输出索引的话,那怎样实现呢?
Foreach循环输出索引值

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

Source Code

再次运行,结果可见:
Foreach循环输出索引值