다음을 통해 공유


CA1841: 사전 Contains 메서드를 선호하십시오

속성
규칙 ID CA1841
제목 Dictionary Contains 메서드를 선호하십시오.
범주 성능
수정 사항이 호환성을 깨뜨리는지 여부 또는 무중단인지 여부 주요 변경 아님
.NET 10에서 기본적으로 사용하도록 설정 제안 사항
적용 가능한 언어 C# 및 Visual Basic

원인

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

규칙 설명

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

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

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

참고하기