Inheriting from List<T> in .NET (vb or C#)

I have been delved in C++ world for a while, but now I'm in .NET world again, VB and C# and I wondered if you have a class that represents a collection of something, and you want the ability to use this in a foreach loop, etc... is it better to implement IEnumerable and IEnumerator yourself or should you inherit from the List<T> where T is the object type in it's singular form?

I know in C++ for example, inheriting from a container is considered a bad idea.

But what about .NET.

EDIT:

It seems my question was slightly misunderstood. I am not unhappy at all with existing collections in .NET. Here is my problem, I have a class called 'Person' and I need a collection called 'Scouts', which I want in an Class called 'Scouts', at this point I'd like to be able to write

foreach Person in Scouts ...

What is the best way to get this Scouts as a collection of People, and be able to use it in a foreach loop?


You said:

I have a class called 'Person' and I need a collection called 'Scouts', which I want in an Class called 'Scouts', at this point I'd like to be able to write

foreach Person in Scouts ...

If I understand you correctly, you want:

class Scouts : IEnumerable<Person>
{
    private List<Person> scouts;

    public IEnumerator<Person> GetEnumerator()
    {
        return scouts.GetEnumerator();
    }
}

In .NET it is rare to implement IEnumerable<T> or derive from List<T> . If you need a dynamic length collection with indexer you could use List<T> directly and if you need a fixed length collection you could use an array T[] . The System.Collections.Generic namespace contains most of the generic collection classes.


The real question is, why would you want to implement your own "collection of something"? That is, why exactly are you not satisfied with existing collections?

Once you answer that question (and are still sure you want to do it), you'd be better off inheriting from one of collections in the System.Collections.ObjectModel namespace - namely, Collection<T> , KeyedCollection<T> , or ReadOnlyCollection<T> , depending on your particular needs.

链接地址: http://www.djcxy.com/p/53872.html

上一篇: C#从Dictionary继承,遍历KeyValuePairs

下一篇: 在.NET(vb或C#)中继承List <T>