使用具標籤的跳躍陳述式(IDE0410)

房產 價值
規則識別碼 IDE0410
Title 使用具標籤的跳躍陳述式
Category Style
子類別 語言規則(程式碼區塊偏好)
適用語言 C# 15+
選項 csharp_style_prefer_labeled_jump_statements

概觀

為了讓巢狀迴圈的控制流程更清楚、更簡潔,當可改用加上標籤的 breakcontinue 陳述式(C# 15+)時,此規則會標記使用 goto 陳述式或布林旗標模式來跳出或繼續執行巢狀迴圈的程式碼。

該規則偵測以下模式:

  • 一個 goto 在巢狀迴圈後立即跳轉到標籤的陳述,該標籤可被替換為 break <label>
  • 會跳到迴圈本體結尾處空標籤的 goto 陳述式(等同於繼續外層迴圈),可改為 continue <label>
  • 布林旗標模式是指將旗標變數設為 true,然後在每一層迴圈中加以檢查,以便將 break 或 continue 向外層巢狀迴圈傳遞;這種模式可改用單一帶標籤的 break <label>continue <label> 來取代。

選項

選項會指定您希望規則強制執行的行為。 如需設定選項的相關資訊,請參閱 選項格式

C# 樣式:偏好已加上標籤的跳躍陳述式

房產 價值 Description
選項名稱 csharp_樣式_偏好具標籤的跳躍陳述式
選項值 true 偏好使用具標籤的跳轉陳述式
false 停用規則
預設選項值 true

Example

以下範例展示了此規則偵測的三種模式:

Goto 被 Break Label 取代

// 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 被 Continue 標籤取代

// 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;
    }
}

旗標模式被中斷標籤取代

// 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

如需詳細資訊,請參閱 如何隱藏程式碼分析警告

另請參閱