Share via


CA2021: 호환되지 않는 형식을 사용하여 Enumerable.Cast<T> 또는 Enumerable.OfType<T> 를 호출하지 마세요.

속성
규칙 ID CA2021
타이틀 호출 Enumerable.Cast<T> 안 함 또는 Enumerable.OfType<T> 호환되지 않는 형식 사용
범주 신뢰성
수정 사항이 주요 변경인지 여부 주요 변경
.NET 8에서 기본적으로 사용 경고로

원인

입력 컬렉션의 형식과 호환되지 않는 형식 매개 변수를 호출 Enumerable.Cast<TResult>(IEnumerable) 하거나 Enumerable.OfType<TResult>(IEnumerable) 지정합니다.

규칙 설명

Enumerable.Cast<TResult>(IEnumerable) 필요한 Enumerable.OfType<TResult>(IEnumerable) 결과를 생성하려면 호환되는 형식이 필요합니다.

확대 및 사용자 정의 변환은 제네릭 형식에서 지원되지 않습니다.

위반 문제를 해결하는 방법

OfType<TResult>(IEnumerable).의 형식 매개 변수에 호환되는 형식을 Cast<TResult>(IEnumerable) 사용합니다.

예시

다음 코드 조각은 위반을 보여 줍니다.

var foods = new List<Food>();
// Violation - Food is incompatible with Beverages.
var drinks = Enumerable.Cast<Beverages>(foods);
// Violation - Food is incompatible with Beverages.
var drinks2 = Enumerable.OfType<Beverages>(foods);

class Food { }
class Bread : Food { }
class Beverages { }
' Violation - Integer is incompatible with String.
Dim a1 = (Array.Empty(Of Integer)()).Cast(Of String)
' Violation - Integer is incompatible with String.
Dim a1 = (Array.Empty(Of Integer)()).OfType(Of String)

다음 코드 조각은 수정 사항을 보여줍니다.

var foods = new List<Food>();
// Bread is compatible with Food.
var breads = Enumerable.Cast<Bread>(foods);
// Bread is compatible with Food.
var breads2 = Enumerable.OfType<Bread>(foods);

class Food { }
class Bread : Food { }
class Beverages { }
' Integer is compatible with Object.
Dim a1 = (Array.Empty(Of Integer)()).Cast(Of Object)
' Integer is compatible with Object.
Dim a1 = (Array.Empty(Of Integer)()).OfType(Of Object)

경고를 표시하지 않는 경우

런타임 예외 또는 예기치 않은 동작(빈 시퀀스)이 발생하므로 이 규칙의 경고를 표시하지 않아야 합니다.