Are Strongly typed ArrayLists the better choice in C#?
When I program in C# , there are times when I need a strongly typed collection:
I often create a class that inherits from 开发者_JAVA百科the ArrayList
:
using System.Collections;
public class Emails: ArrayList
{
public new Email this[int i]
{
get
{
return (Email)base[i];
}
set
{
base[i] = value;
}
}
}
I realize this is probably not the correct way to inherit from a collection. If I want to inherit from a strongly typed collection in C#, how should I do it, and what class should I choose to inherit from?
What you want is a generic, like List<T>
.
public class Emails : List<Email>
{
}
This has all of the methods of ArrayList and then some, and you get type safety without having to do any extra work.
Note, however, that inheriting from List<T>
can sometimes cause you more trouble than it's worth. A better idea is to implement ICollection<T>
or IEnumerable<T>
, and use the List<T>
internally to implement the interface.
Forget both ArrayList and List. The "right" thing to do would be to derive from Collection and call your class something that ends in Collection.
public sealed class EmailCollection : Collection<Email>
{
}
If you're not stuck with .Net 1.1, you really should forget about ArrayList
and use the generic List<T>
instead. You get strong typing and better performances to boot.
In general new
should be avoided for member declaration if at all possible.
As of C# 2 though you can use generics. List<email> list = new List<email>();
Not really, that's what generics are for.
Generics seem much more appropriate. For example,
List<email>
in this case. Why reinvent the wheel and perform worse?
If you use .net 2.0 or + i would go with a generic collection
精彩评论