简体   繁体   English

强类型ArrayLists是C#中更好的选择吗?

[英]Are Strongly typed ArrayLists the better choice in C#?

When I program in C# , there are times when I need a strongly typed collection: 当我使用C#编程时,有时我需要一个强类型集合:

I often create a class that inherits from the ArrayList : 我经常创建一个继承自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? 如果我想继承C#中的强类型集合,我应该怎么做,我应该选择继承哪个类?

What you want is a generic , like List<T> . 你想要的是一个通用的 ,比如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. 这有ArrayList的所有方法,然后是一些,你可以获得类型安全而无需做任何额外的工作。

Note, however, that inheriting from List<T> can sometimes cause you more trouble than it's worth. 但请注意,继承自List<T>有时会给您带来更多麻烦而不是它的价值。 A better idea is to implement ICollection<T> or IEnumerable<T> , and use the List<T> internally to implement the interface. 更好的想法是实现ICollection<T>IEnumerable<T> ,并在内部使用List<T>来实现接口。

Forget both ArrayList and List. 忘记ArrayList和List。 The "right" thing to do would be to derive from Collection and call your class something that ends in Collection. 要做的“正确”的事情是从Collection派生出来并将你的类称为以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. 如果你没有坚持.Net 1.1,你真的应该忘记ArrayList并使用通用List<T> You get strong typing and better performances to boot. 您可以获得强大的打字和更好的性能。

In general new should be avoided for member declaration if at all possible. 一般来说,如果可能的话,应该避免new成员申报。

As of C# 2 though you can use generics. 从C#2开始,虽然你可以使用泛型。 List<email> list = new List<email>();

不是,这就是泛型的用途。

Generics seem much more appropriate. 仿制药看起来更合适。 For example, 例如,

List<email> 

in this case. 在这种情况下。 Why reinvent the wheel and perform worse? 为什么重新发明轮子并且表现更差?

如果您使用.net 2.0或+我将使用通用集合

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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