Collections vs. IEnumerable
What are the advantages/disadvantages of inheriting 开发者_StackOverflow社区collection vs. implementing iEnumerable()
It's usually a mistake (IMO) to derive a class from one of the collection types. I would do it to create a new general purpose collection type - but if the class has some "business" purpose, and just happens to act like a collection in other ways, I think it's not a good idea to derive from a collection class.
If you implement IEnumerable<T>
you're effectively giving the message that your class can be used as a sequence of T
(probably for a particular, concrete T
) but there's more to it than that: it has non-collection abilities too. Of course, you may not even need to implement it yourself - you could have properties or methods which return an appropriate sequence. It depends on the use case, really.
Don't forget that you only get to derive from one base class in .NET... so think very carefully before you use up that one chance on a collection type.
Implementing IEnumerable is almost never necessary. There is almost always a suitable collection you can just use.
For me, List<T>
and Dictionary<Tkey,TValue>
cover 90% of what I usually need to do.
精彩评论