是的,C# 的 for 循环可以处理集合(Collection)。在 C# 中,集合通常是一个实现了 IEnumerable 或 IEnumerator 接口的类,例如 List<T>、Dictionary<TKey, TValue>、HashSet<T> 等。
以下是一些使用 for 循环遍历集合的示例:
- 遍历 List<int>:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Count; i++)
{
    Console.WriteLine(numbers[i]);
}
- 遍历 Dictionary<string, int>:
Dictionary<string, int> fruits = new Dictionary<string, int>
{
    { "apple", 5 },
    { "banana", 8 },
    { "orange", 3 }
};
foreach (KeyValuePair<string, int> fruit in fruits)
{
    Console.WriteLine($"{fruit.Key}: {fruit.Value}");
}
注意:虽然这里使用了 foreach 循环,但它实际上是遍历集合的一种简便方法。实际上,foreach 循环底层也是使用 for 循环来遍历集合。因此,你可以根据需要选择使用 for 循环或 foreach 循环来遍历集合。

 便宜VPS测评
便宜VPS测评









