CA2227:集合屬性應該為唯讀

屬性
規則識別碼 CA2227
標題 集合屬性應該為唯讀
類別 使用方式
修正程式是中斷或非中斷 中斷
預設在 .NET 8 中啟用 No

原因

外部可見且可寫入的屬性是實作 System.Collections.ICollection的型別。 此規則會忽略數位、索引器(名稱為 'Item' 的屬性)、不可變的集合、只讀集合和許可權集合。

檔案描述

可寫入的集合屬性可讓使用者以完全不同的集合取代集合。 只讀或 init-only 屬性會停止取代集合,但仍允許設定個別成員。 如果取代集合是目標,慣用的設計模式是包含方法以移除集合中的所有元素,以及重新填入集合的方法。 如需此模式的範例,請參閱 類別ClearSystem.Collections.ArrayListAddRange 方法。

二進位和 XML 串行化都支援集合的唯讀屬性。 類別System.Xml.Serialization.XmlSerializer具有實作 和 System.Collections.IEnumerable 才能串行化之型ICollection別的特定需求。

如何修正違規

若要修正此規則的違規,請將 屬性設為唯讀或 僅限 init。 如果設計需要它,請新增方法來清除和重新填入集合。

隱藏警告的時機

如果 屬性是資料傳輸物件 (DTO) 類別的一部分,您可以隱藏警告。

否則,請勿隱藏此規則的警告。

隱藏警告

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

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

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

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

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

範例

下列範例示範具有可寫入集合屬性的類型,並示範如何直接取代集合。 此外,它會顯示使用 和 AddRange 方法來取代唯讀集合屬性的慣用Clear方式。

public class WritableCollection
{
    public ArrayList SomeStrings
    {
        get;

        // This set accessor violates rule CA2227.
        // To fix the code, remove this set accessor or change it to init.
        set;
    }

    public WritableCollection()
    {
        SomeStrings = new ArrayList(new string[] { "one", "two", "three" });
    }
}

class ReplaceWritableCollection
{
    static void Main2227()
    {
        ArrayList newCollection = new ArrayList(new string[] { "a", "new", "collection" });

        WritableCollection collection = new WritableCollection();

        // This line of code demonstrates how the entire collection
        // can be replaced by a property that's not read only.
        collection.SomeStrings = newCollection;

        // If the intent is to replace an entire collection,
        // implement and/or use the Clear() and AddRange() methods instead.
        collection.SomeStrings.Clear();
        collection.SomeStrings.AddRange(newCollection);
    }
}
Public Class WritableCollection

    ' This property violates rule CA2227.
    ' To fix the code, add the ReadOnly modifier to the property:
    ' ReadOnly Property SomeStrings As ArrayList
    Property SomeStrings As ArrayList

    Sub New()
        SomeStrings = New ArrayList(New String() {"one", "two", "three"})
    End Sub

End Class

Class ViolatingVersusPreferred

    Shared Sub Main2227()
        Dim newCollection As New ArrayList(New String() {"a", "new", "collection"})

        Dim collection As New WritableCollection()

        ' This line of code demonstrates how the entire collection
        ' can be replaced by a property that's not read only.
        collection.SomeStrings = newCollection

        ' If the intent is to replace an entire collection,
        ' implement and/or use the Clear() and AddRange() methods instead.
        collection.SomeStrings.Clear()
        collection.SomeStrings.AddRange(newCollection)
    End Sub

End Class

另請參閱