是的,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 循環來遍歷集合。