CA2011:請勿在屬性的設定函式中指派值

屬性
規則識別碼 CA2011
職稱 請勿在屬性 setter 中指定屬性值
類別 可靠性
修正是造成中斷還是不中斷 不中斷
在 .NET 10 中預設啟用 作為建議
適用語言 C# 與 Visual Basic

原因

不小心在 set 存取子中為屬性指派了值。

規則描述

將屬性指派給其 set 存取子 本身,會導致遞迴呼叫 set 存取子的無限鏈。 這會在執行期間導致一個 StackOverflowException。 當屬性與儲存屬性值的後備欄位名稱相似時,這類錯誤很常見。 它不會將值指派給備份欄位,而是不小心指派給屬性本身。

如何修正違規

若要修正違規,請將違規的屬性指派替換為備份欄位的指派,或轉換為使用自動屬性。 例如,下列代碼段會顯示違反規則,以及修正規則的幾種方式:

public class C
{
    // Backing field for property 'P'
    private int p;

    public int P
    {
        get
        {
            return p;
        }
        set
        {
            // CA2011: Accidentally assigned to property, instead of the backing field.
            P = value;
        }
    }
}
public class C
{
    // Backing field for property 'P'
    private int _p;

    public int P
    {
        get
        {
            return _p;
        }
        set
        {
            // Option 1: Assign to backing field and rename the backing field for clarity.
            _p = value;
        }
    }
}
public class C
{
    // Option 2: Use auto-property.
    public int P { get; set; }
}

隱藏警告的時機

如果您確定已有條件地保護對 set 存取子的遞迴呼叫,以防止無限遞迴,則可以抑制此規則的違規。

隱藏警告

如果您只想要隱藏單一違規,請將預處理器指示詞新增至原始程式檔以停用,然後重新啟用規則。

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

若要停用檔案、資料夾或專案的規則,請在組態檔中將其嚴重性設為 none

[*.{cs,vb}]
dotnet_diagnostic.CA2011.severity = none

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

另請參閱