Share via


(IDE0303)에 컬렉션 Create() 식 사용

속성
규칙 ID IDE0303
타이틀 Create에 컬렉션 식 사용
범주 스타일
하위 범주 언어 규칙(식 수준 기본 설정)
해당 언어 C# 12+
옵션 dotnet_style_prefer_collection_expression

개요

이 규칙은 컬렉션 생성 메서드(특성을 사용CollectionBuilderAttribute)로 지정된 메서드 또는 유사한 메서드를 사용하여 컬렉션을 초기화하고 컬렉션 식([...])으로 바꾸도록 제공하는 위치에 Create() 플래그를 지정합니다.

Create() 메서드는 변경할 수 없는 컬렉션에 일반적입니다(예 ImmutableArray.Create(1, 2, 3): .).

참고 항목

이 규칙에는 컬렉션 식 패턴을 옵트인하는 변경할 수 없는 API(예: System.Collections.Immutable)의 최신 버전이 필요합니다.

옵션

옵션은 규칙을 적용할 동작을 지정합니다. 옵션 구성에 대한 자세한 내용은 옵션 형식을 참조하세요.

dotnet_style_prefer_collection_expression

속성 설명
옵션 이름 dotnet_style_prefer_collection_expression
옵션 값 true | when_types_exactly_match 예를 들어 ImmutableArray<int> i = ImmutableArray.Create(1, 2, 3);형식이 정확히 일치하는 경우에만 컬렉션 식을 사용하는 것이 좋습니다.
when_types_loosely_match
(.NET 9 이상 버전)*
예를 들어 IEnumerable<int> i = ImmutableArray.Create(1, 2, 3);형식이 느슨하게 일치하는 경우에도 컬렉션 식을 사용하는 것이 좋습니다. 대상 형식은 오른쪽의 형식과 일치하거나 다음 형식 IEnumerable<T>IReadOnlyCollection<T>ICollection<T>IList<T>IReadOnlyList<T>중 하나여야 합니다.
false | never 규칙을 사용하지 않도록 설정합니다.
기본 옵션 값 true .NET 8에서
when_types_loosely_match .NET 9 이상 버전

*이 옵션을 사용할 때 코드 수정은 코드의 의미 체계를 변경할 수 있습니다.

예시

// Code with violations.
ImmutableArray<int> i = ImmutableArray.Create(1, 2, 3);
IEnumerable<int> j = ImmutableArray.Create(1, 2, 3);

// Fixed code.
ImmutableArray<int> i = [1, 2, 3];
IEnumerable<int> j = [1, 2, 3];

다음 코드 조각은 주석이 추가된 사용자 지정 형식의 예제를 CollectionBuilderAttribute보여줍니다.

public class Program
{
    public static void Main()
    {
        // IDE0303 violation.
        MyCollection<int> c = MyCollection.Create(1, 2, 3);

        // IDE0303 fixed code.
        MyCollection<int> c = [1, 2, 3];
    }
}

static partial class MyCollection
{
    public static MyCollection<T> Create<T>(System.ReadOnlySpan<T> values) => default;
    public static MyCollection<T> Create<T>(T t1, T t2, T t3) => default;
}

[CollectionBuilder(typeof(MyCollection), "Create")]
class MyCollection<T> : IEnumerable<T>
{
    public IEnumerator<T> GetEnumerator() => default;
    IEnumerator IEnumerable.GetEnumerator() => default;
}

경고 표시 안 함

단일 위반만 표시하지 않으려면 원본 파일에 전처리기 지시문을 추가하여 규칙을 사용하지 않도록 설정한 후 다시 사용하도록 설정합니다.

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

파일, 폴더 또는 프로젝트에 대한 규칙을 사용하지 않도록 설정하려면 구성 파일에서 심각도를 none으로 설정합니다.

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

모든 코드 스타일 규칙을 사용하지 않도록 설정하려면 구성 파일에서 범주 Style의 심각도를 none으로 설정합니다.

[*.{cs,vb}]
dotnet_analyzer_diagnostic.category-Style.severity = none

자세한 내용은 방법: 코드 분석 경고 표시 안 함을 참조하세요.

참고 항목