공분산 및 IList 제한 이해
공분산은 참조 유형을 기본 또는 인터페이스의 변수에 할당할 수 있는 프로그래밍 원칙입니다. 유형. 그러나 이는 컬렉션, 특히 IList 인터페이스를 고려할 때 딜레마를 야기합니다.
IList는 인덱스 액세스가 있는 컬렉션을 나타내므로 인덱스로 요소를 검색할 수 있습니다. 불행하게도 List
인덱스 액세스가 포함된 공변 컬렉션을 위한 솔루션
이러한 제한에도 불구하고 다음을 달성할 수 있는 방법이 있습니다. 색인화된 액세스를 유지하면서 공변적 동작
1. ReadOnlyCollections(.NET 4.5 이상)
IReadOnlyList
2. 사용자 지정 래퍼
이전 버전의 .NET에서 인덱싱된 액세스가 포함된 공변 컬렉션이 필요한 경우 래퍼 클래스를 만들 수 있습니다. 래퍼 클래스는 IList
다음 코드는 CovariantList
public static class Covariance { public static IIndexedEnumerable<T> AsCovariant<T>(this IList<T> tail) { return new CovariantList<T>(tail); } private class CovariantList<T> : IIndexedEnumerable<T> { private readonly IList<T> tail; public CovariantList(IList<T> tail) { this.tail = tail; } public T this[int index] { get { return tail[index]; } } public IEnumerator<T> GetEnumerator() { return tail.GetEnumerator();} IEnumerator IEnumerable.GetEnumerator() { return tail.GetEnumerator(); } public int Count { get { return tail.Count; } } } } public interface IIndexedEnumerable<out T> : IEnumerable<T> { T this[int index] { get; } int Count { get; } }
위 내용은 .NET 컬렉션에서 인덱싱된 액세스를 사용하여 공변 동작을 어떻게 달성할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!