C#中for循环的变种有哪些
C#中for循环的变种有以下几种:
- foreach循环:用于遍历集合类对象中的元素。
foreach (var item in collection)
{
// do something
}
- for循环逆序遍历:从集合末尾开始遍历。
for (int i = collection.Length - 1; i >= 0; i--)
{
// do something
}
- for循环嵌套:在循环内部嵌套另一个循环。
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
// do something
}
}
- 增强的for循环:C# 8.0引入了增强的foreach循环,可同时访问集合中的索引和元素。
foreach (var (item, index) in collection.WithIndex())
{
// do something
}
- while循环:当条件满足时会一直执行循环。
while (condition)
{
// do something
}
- do-while循环:先执行一次循环体,然后判断条件是否满足。
do
{
// do something
} while (condition);
相关问答