使用带标签的跳转语句(IDE0410)

资产 价值
规则 ID IDE0410
标题 使用带标签的跳转语句
Category Style
子类别 语言规则(代码块首选项)
适用的语言 C# 15+
Options csharp_style_prefer_labeled_jump_statements

概述

为了使嵌套循环控制流更清晰、更简洁,此规则会标记使用 goto 语句或布尔标志模式来跳出或继续嵌套循环的代码,因为在这种情况下可以改用 带标签的 break 或 continue 语句(C# 15+)。

该规则检测以下模式:

  • 在嵌套循环后立即跳转到标签的 goto 语句,可以被替换为 break <label>。
  • 一个会跳转到循环体末尾的空标签的 goto 语句(实际上会继续外层循环),可以被替换为 continue <label>。
  • 布尔标志模式,其中标志变量设置为 true,然后在每个循环级别被检查,以通过嵌套循环向外传播中断或继续,嵌套循环可以用单个标记的 break <label> 或 continue <label> 来替换。

选项

选项指定你希望规则强制实施的行为。 若要了解如何配置选项,请参阅选项格式。

csharp_style_首选带标签的跳转语句

资产 价值 说明
选项名称 csharp_style_prefer_labeled_jump_statements
选项值 true 优先使用带标签的跳转语句
false 禁用规则
默认选项值 true

Example

以下示例显示了此规则检测到的三种模式:

goto 被 break 标签替换

// Code with violations.
for (int x = 0; x < 10; x++)
{
    for (int y = 0; y < 10; y++)
    {
        if (x * y > 20)
            goto found;
    }
}

found:
Console.WriteLine("Done");

// Fixed code.
found: for (int x = 0; x < 10; x++)
{
    for (int y = 0; y < 10; y++)
    {
        if (x * y > 20)
            break found;
    }
}

Console.WriteLine("Done");

goto 替换为“继续”标签

// Code with violations.
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        if (j == 5)
            goto next;
    }

    next: ; // The empty statement is required; a label in C# must be followed by a statement.
}

// Fixed code.
next: for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        if (j == 5)
            continue next;
    }
}

标志模式被 Break 标签替换

// Code with violations.
bool found = false;
for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        if (i * j > 20)
        {
            found = true;
            break;
        }
    }

    if (found)
        break;
}

// Fixed code.
loop_i: for (int i = 0; i < 10; i++)
{
    for (int j = 0; j < 10; j++)
    {
        if (i * j > 20)
        {
            break loop_i;
        }
    }
}

禁止显示警告

如果只想抑制单个冲突,请将预处理器指令添加到源文件以禁用该规则,然后重新启用该规则。

#pragma warning disable IDE0410
// The code that's violating the rule is on this line.
#pragma warning restore IDE0410

若要禁用文件、文件夹或项目的规则,请在none中将其严重性设置为。

[*.cs]
dotnet_diagnostic.IDE0410.severity = none

若要禁用所有代码样式规则,请在Style中将类别 none 的严重性设置为 。

[*.cs]
dotnet_analyzer_diagnostic.category-Style.severity = none

有关详细信息,请参阅 如何禁止显示代码分析警告。

另见