foreach怎么遍历集合
在C#中,可以使用foreach循环来遍历集合。以下是使用foreach循环遍历集合的示例代码:
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
Console.WriteLine(number);
}
在上述示例中,我们定义了一个List<int>类型的集合numbers,然后使用foreach循环遍历集合中的每个元素,并将其打印到控制台上。输出结果将是:
1
2
3
4
5
请注意,foreach循环只能用于实现了IEnumerable接口的集合类型。
原文地址: https://www.cveoy.top/t/topic/iObh 著作权归作者所有。请勿转载和采集!