"일꾼이 일을 잘하려면 먼저 도구를 갈고 닦아야 한다." - 공자, 『논어』.
첫 장 > 프로그램 작성 > .NET 컬렉션에서 인덱스 액세스로 공분산 동작을 어떻게 달성 할 수 있습니까?

.NET 컬렉션에서 인덱스 액세스로 공분산 동작을 어떻게 달성 할 수 있습니까?

2025-02-10에 게시되었습니다
검색:999

How Can I Achieve Covariant Behavior with Indexed Access in .NET Collections?

공분산 및 ilist 제한 이해

공분산은 참조 유형을 기본 또는 인터페이스의 변수에 할당 할 수있는 원칙입니다. 유형. 그러나 이것은 컬렉션과 관련하여, 특히 ILIST 인터페이스를 고려할 때 딜레마를 제시합니다.

ILIST는 인덱스 액세스가있는 컬렉션을 나타내므로 인덱스별로 요소를 검색 할 수 있습니다. 불행히도 List 와 같은 내장 .NET 컬렉션은 GET 및 SET 인덱서를 모두 구현하여 완전히 공분산이되는 것을 방지합니다.

이 제한에도 불구하고, 인덱스 된 액세스를 유지하면서 공분산 행동을 달성하는 방법이 있습니다.

1. readOnlyCollection (.NET 4.5에서) 그들은 Get Indexer 만 있으므로 공분산 시나리오에 적합합니다. List 및 ReadOnLyCollection 두 인터페이스를 구현합니다.

2. Custom Wrapper

이전 버전의 .NET에서 인덱스 액세스가있는 공분산 컬렉션이 필요한 경우 래퍼 클래스를 만들 수 있습니다. 래퍼 클래스는 ilist 를 캡슐화하고 Get Indexer 및 ienumerable 인터페이스 만 노출시킵니다.

public static class Covariance
{
    public static IIndexedEnumerable AsCovariant(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 ascovariant (이 ilist 꼬리) { 새로운 Cobariantlist (Tail)를 반환합니다. } 개인 클래스 Covariantlist : iindexedEnumerable { 비공개 판독 꼬리; Public Cobariantlist (Ilist Tail) { this.tail = 꼬리; } 공개 t이 [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; }} } } 공개 인터페이스 iindexedEnumerable : ienumerable { t이 [int index] {get; } int count {get; } } How Can I Achieve Covariant Behavior with Indexed Access in .NET Collections?

최신 튜토리얼 더>

부인 성명: 제공된 모든 리소스는 부분적으로 인터넷에서 가져온 것입니다. 귀하의 저작권이나 기타 권리 및 이익이 침해된 경우 자세한 이유를 설명하고 저작권 또는 권리 및 이익에 대한 증거를 제공한 후 이메일([email protected])로 보내주십시오. 최대한 빨리 처리해 드리겠습니다.

Copyright© 2022 湘ICP备2022001581号-3