次の方法で共有


CA2227:Collection プロパティは読み取り専用でなければなりません

プロパティ
ルール ID CA2227
Title Collection プロパティは読み取り専用でなければなりません
[カテゴリ] 使用方法
修正が破壊的か非破壊的か 速報
.NET 10 で既定で有効 いいえ
該当する言語 C# と Visual Basic

原因

外部から参照できる、書き込み可能なプロパティの型は System.Collections.ICollection を実装します。 この規則は、配列、インデクサー (名前が 'Item' のプロパティ)、変更できないコレクション、読み取り専用コレクション、およびアクセス許可セットを無視します。

規則の説明

書き込み可能なコレクション プロパティを使用すると、ユーザーはコレクションをまったく異なるコレクションに置き換えることができます。 読み取り専用プロパティまたは init 専用 プロパティを使用すると、コレクションは置き換えられなくなりますが、個々のメンバーを設定することはできます。 コレクションを置き換えることを目的とする場合、推奨される設計パターンは、コレクションからすべての要素を削除するメソッドと、コレクションを再作成するメソッドを含める方法です。 このパターンの例については、Clear クラスの AddRange および System.Collections.ArrayList メソッドを参照してください。

バイナリ シリアル化と XML シリアル化の両方で、コレクションである読み取り専用プロパティがサポートされます。 System.Xml.Serialization.XmlSerializer クラスには、シリアル化可能なICollectionSystem.Collections.IEnumerableを実装する型に固有の要件があります。

違反の修正方法

この規則の違反を修正するには、次のいずれかの方法を使用します。

  • プロパティを読み取り専用または init 専用にします。 読み取り専用プロパティまたは init 専用 プロパティを使用すると、コレクションが置き換えられず、個々のメンバーを設定できます。 デザインでコレクションの内容を置き換える必要がある場合は、コレクションをクリアして再作成するメソッドを追加します。 このパターンの例については、 ArrayList.Clear メソッドと ArrayList.AddRange メソッドを参照してください。

  • プロパティ型を読み取り専用コレクション型に変更します。 呼び出し元がコレクションを変更する必要がない場合は、プロパティの種類を読み取り専用のコレクション ( ReadOnlyCollection<T> など) に変更します。 この方法では、型シグネチャで読み取り専用の意図が明示的になります。

  • プロパティの型をスレッド セーフな同時実行コレクション型に変更し、プロパティの読み取り専用を維持します。 デザインでコレクションを同時に変更するために複数のスレッドが必要な場合は、型が同時実行コレクションである読み取り専用プロパティ (セッターなし) を公開します ( ConcurrentBag<T>など)。 CA2227 は、コレクション型ではなく、書き込み可能なコレクション プロパティによってトリガーされるため、プロパティは引き続き読み取り専用である必要があります。 同時実行コレクションの選択は、返されたコレクション インスタンスのスレッド セーフな変更にのみ対処します。

どのようなときに警告を抑制するか

プロパティがデータ転送オブジェクト (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

詳細については、「コード分析の警告を抑制する方法」を参照してください。

次の例は、書き込み可能なコレクション プロパティを持つ型と、コレクションを直接置き換える方法を示しています。 また、 Clear メソッドと AddRange メソッドを使用して、読み取り専用のコレクション プロパティを置き換える方法も示します。

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 = ["a", "new", "collection"];

        WritableCollection collection = new()
        {
            // This line of code demonstrates how the entire collection
            // can be replaced by a property that's not read only.
            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

関連項目