简体   繁体   中英

Implementing my own generic collection in C#

I am trying to write my own generic collection ( List<T> ) in C# but got confused with the interfaces. As I understand, in order to create my own collection, I need to implement several interfaces, like ICollection, IList, IEnumerator, IEnumerable etc. But I can't really understand which ones I need. Thanks in advance

You have to implement IList<T> for access to the collection's items by their index. IList<T> inherits from ICollection<T> , IEnumerable<T> and IEnumerable , so you get those anyway.

For a more basic collection without access to an item by index, you implement ICollection<T> , which comes with IEnumerable<T> and IEnumerable through inheritance.

You can additionally implement IReadOnlyList<T> (or IReadOnlyCollection<T> respectively), but that is usually not necessary.

You should also look into inheriting from System.Collections.ObjectModel.Collection<T> instead, which is the recommended way, because the usual boilerplate interface implementations are already done for you and you can concentrate on the parts that make your collection special.

What is your collection for? If you implement IEnumerable<T> (which entails implementing IEnumerable , then you've an enumerable object. If you've also got an Add() method then you've got an enumerable object that works with collection initialisation. Beyond that, look at the common collection interfaces and ask if they are useful to your use cases, particularly ICollection<T> (adding and removal in particular) and IList<T> (indexing in particular).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM