Home >Backend Development >C++ >How Can I Achieve Covariance with Index Support in Collections?
Covariance in Collections with Index Support
Covariance in collections allows derived items to be stored in a collection declared for a base type. However, the default covariant collection, IEnumerable, lacks index support.
As the questioner notes, upcasting a List
Possible Solutions
From .NET 4.5 onwards, IReadOnlyList
Creating a Covariant Wrapper
If a writable collection with index support is required, an extension method can be created to wrap an 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> { // Implementation... } }
This wrapper class, CovariantList
By calling AsCovariant
The above is the detailed content of How Can I Achieve Covariance with Index Support in Collections?. For more information, please follow other related articles on the PHP Chinese website!