分享方式:


CA2011:請勿在屬性 setter 中指派屬性

屬性
規則識別碼 CA2011
標題 請勿在屬性 setter 中指派屬性
類別 可靠性
修正程式是中斷或非中斷 不中斷
預設在 .NET 8 中啟用 建議

原因

不小心在自己的 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

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

另請參閱