在C#中,foreach循环无法直接获取索引。但可以使用for循环来获取索引。以下是一个示例:

string[] fruits = { "apple", "banana", "orange" };

for (int i = 0; i < fruits.Length; i++)
{
    string fruit = fruits[i];
    Console.WriteLine("Index: " + i + ", Fruit: " + fruit);
}

在上面的示例中,通过使用for循环和索引i,我们可以获取每个元素的索引。输出将是:

Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: orange

注意,foreach循环主要用于遍历集合,而不是获取索引。如果需要索引,最好使用for循环来代替。

C# foreach 获取index

原文地址: https://www.cveoy.top/t/topic/jaiU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录