CA2227: 컬렉션 속성은 읽기 전용이어야 합니다.

속성
규칙 ID CA2227
타이틀 컬렉션 속성은 읽기 전용이어야 합니다.
범주 사용 현황
수정 사항이 주요 변경인지 여부 주요 변경
.NET 8에서 기본적으로 사용 아니요

원인

외부에서 볼 수 있는 쓰기 가능 속성은 System.Collections.ICollection을 구현하는 형식입니다. 이 규칙은 배열, 인덱서(이름이 ‘항목’ 인 속성), 변경할 수 없는 컬렉션, 읽기 전용 컬렉션, 권한 집합을 무시합니다.

규칙 설명

쓰기 가능한 컬렉션 속성을 통해 사용자는 컬렉션을 다른 컬렉션으로 바꿀 수 있습니다. 읽기 전용 또는 초기화 전용 속성은 컬렉션을 대체하지 못하도록 하지만, 개별 멤버는 계속해서 설정할 수 있습니다. 컬렉션을 대체하는 것이 목표인 경우 기본 디자인 패턴은 컬렉션에서 모든 요소를 제거하는 메서드와 컬렉션을 다시 채우는 메서드를 포함하는 것입니다. 이 패턴의 예는 System.Collections.ArrayList 클래스의 Clear 메서드 및 AddRange 메서드를 참조하세요.

이진 및 XML serialization은 모두 컬렉션인 읽기 전용 속성을 지원합니다. System.Xml.Serialization.XmlSerializer 클래스에는 직렬화가 가능하도록 ICollectionSystem.Collections.IEnumerable을 구현하는 형식에 대한 특정 요구 사항이 있습니다.

위반 문제를 해결하는 방법

규칙 위반 문제를 해결하려면 속성을 읽기 전용 또는 초기화 전용으로 설정하세요. 디자인에 필요한 경우에는 컬렉션을 지우고 다시 채우는 메서드를 추가합니다.

경고를 표시하지 않는 경우

속성이 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 = 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

참고 항목