Share via


CA1841: 사전 Contains 메서드 사용

속성
규칙 ID CA1841
타이틀 Prefer Dictionary Contains 메서드
범주 성능
수정 사항이 주요 변경인지 여부 주요 변경 아님
.NET 8에서 기본적으로 사용 제안 사항

원인

이 규칙은 사전 자체에서의 ContainsKey 또는 ContainsValue 메서드 호출로 바꿀 수 있는 IDictionary<TKey,TValue>Keys 또는 Values 컬렉션에서의 Contains 메서드 호출을 찾습니다.

규칙 설명

Keys 또는 Values 컬렉션에서 Contains를 호출하면 사전 자체에서 ContainsKey 또는 ContainsValue를 호출하는 것보다 비용이 더 많이 들 수 있습니다.

  • 대부분의 사전 구현에서 키 및 값 컬렉션을 지연 인스턴스화하므로 Keys 또는 Values 컬렉션에 액세스하면 추가 할당이 발생할 수 있습니다.
  • 키 또는 값 컬렉션에서 명시적 인터페이스 구현을 사용하여 ICollection<T>의 메서드를 숨기는 경우 IEnumerable<T>의 확장 메서드를 호출하게 될 수 있습니다. 이로 인해 성능이 저하될 수 있으며, 키 컬렉션에 액세스할 때는 특히 그렇습니다. 대부분의 사전 구현에서는 키에 대한 빠른 O(1) 포함 검사를 제공할 수 있지만, IEnumerable<T>Contains 확장 메서드는 일반적으로 느린 O(n) 포함 검사를 수행합니다.

위반 문제를 해결하는 방법

위반 문제를 해결하려면 dictionary.Keys.Contains 또는 dictionary.Values.Contains 호출을 각각 dictionary.ContainsKey 또는 dictionary.ContainsValue 호출로 바꿉니다.

다음 코드 조각에서는 위반 문제의 예제와 해결 방법을 보여 줍니다.

using System.Collections.Generic;
// Importing this namespace brings extension methods for IEnumerable<T> into scope.
using System.Linq;

class Example
{
    void Method()
    {
        var dictionary = new Dictionary<string, int>();

        //  Violation
        dictionary.Keys.Contains("hello world");

        //  Fixed
        dictionary.ContainsKey("hello world");

        //  Violation
        dictionary.Values.Contains(17);

        //  Fixed
        dictionary.ContainsValue(17);
    }
}
Imports System.Collection.Generic
' Importing this namespace brings extension methods for IEnumerable(Of T) into scope.
' Note that in Visual Basic, this namespace is often imported automatically throughout the project.
Imports System.Linq

Class Example
    Private Sub Method()
        Dim dictionary = New Dictionary(Of String, Of Integer)

        ' Violation
        dictionary.Keys.Contains("hello world")

        ' Fixed
        dictionary.ContainsKey("hello world")

        ' Violation
        dictionary.Values.Contains(17)

        ' Fixed
        dictionary.ContainsValue(17)
    End Sub
End Class

경고를 표시하지 않는 경우

문제의 코드가 성능에 중요하지 않은 경우 이 규칙에서 경고를 표시하지 않도록 해도 안전합니다.

경고 표시 안 함

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

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

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

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

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

참고 항목