공분산 및 ilist 제한 이해
공분산은 참조 유형을 기본 또는 인터페이스의 변수에 할당 할 수있는 원칙입니다. 유형. 그러나 이것은 컬렉션과 관련하여, 특히 ILIST 인터페이스를 고려할 때 딜레마를 제시합니다.
ILIST는 인덱스 액세스가있는 컬렉션을 나타내므로 인덱스별로 요소를 검색 할 수 있습니다. 불행히도 List
이 제한에도 불구하고, 인덱스 된 액세스를 유지하면서 공분산 행동을 달성하는 방법이 있습니다.
1. readOnlyCollection (.NET 4.5에서) 그들은 Get Indexer 만 있으므로 공분산 시나리오에 적합합니다. List
이전 버전의 .NET에서 인덱스 액세스가있는 공분산 컬렉션이 필요한 경우 래퍼 클래스를 만들 수 있습니다. 래퍼 클래스는 ilist
public static class Covariance { public static IIndexedEnumerableAsCovariant (this IList tail) { return new CovariantList (tail); } private class CovariantList : IIndexedEnumerable { private readonly IList tail; public CovariantList(IList tail) { this.tail = tail; } public T this[int index] { get { return tail[index]; } } public IEnumerator GetEnumerator() { return tail.GetEnumerator();} IEnumerator IEnumerable.GetEnumerator() { return tail.GetEnumerator(); } public int Count { get { return tail.Count; } } } } public interface IIndexedEnumerable : IEnumerable { T this[int index] { get; } int Count { get; } }
public static class 공분산
{
public static iindexedenumerable
부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.
Copyright© 2022 湘ICP备2022001581号-3