c#

c# for循环支持哪些语法

小樊
84
2024-11-15 20:43:11
栏目: 编程语言

C# 的 for 循环支持以下语法:

  1. 基本 for 循环:
for (initialization; condition; increment)
{
    // 循环体(代码块)
}

示例:

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i);
}
  1. 增强型 for 循环(foreach 循环):
foreach (element in collection)
{
    // 循环体(代码块)
}

示例:

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
    Console.WriteLine(number);
}
  1. 跳过循环的某次迭代:
for (initialization; condition; increment)
{
    if (skipCondition)
    {
        skipCondition = false; // 重置跳过条件
        continue; // 跳过本次循环迭代,继续下一次迭代
    }

    // 循环体(代码块)
}

示例:

bool shouldSkip = true;
for (int i = 0; i < 10; i++)
{
    if (shouldSkip)
    {
        shouldSkip = false;
        continue;
    }

    Console.WriteLine(i);
}

0
看了该问题的人还看了