温馨提示×

C#中for循环的变种有哪些

c#
小樊
82
2024-06-24 23:54:39
栏目: 编程语言

C#中for循环的变种有以下几种:

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

0