Covariance and IList: Extending Collections for Index Lookups
In C#, covariant collections allow retrieving items from a parent collection using a child collection. However, the standard IEnumerable
Since List
To address this issue, .NET 4.5 and later introduce IReadOnlyList
Both List
However, if you need a covariant collection with both get and set indexers, options are limited. A potential solution is to wrap the existing IList
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 T this[int index] => tail[index]; public IEnumerator<T> GetEnumerator() => tail.GetEnumerator(); public int Count => tail.Count; } } public interface IIndexedEnumerable<out T> : IEnumerable<T> { T this[int index] { get; } int Count { get; } }
This approach provides a covariant collection that supports both IEnumerable
The above is the detailed content of How Can I Achieve Covariant Collections with Index Lookup in C#?. For more information, please follow other related articles on the PHP Chinese website!