4

我认为.net 3.0 中有某种方法可以为数组列表提供一个类型,这样它就不会只返回 Object,但我在这样做时遇到了麻烦。是否可以?如果是这样,怎么做?

4

3 回答 3

14

List<T>在 .NET 2.0 中引入了泛型:

using System.Collections.Generic;

var list = new List<int>();
list.Add(1);
list.Add("string"); //compile-time error!
int i = list[0];
于 2008-09-27T22:00:51.093 回答
3

您可能正在寻找<T>自 .NET 2.0 起可用的 List ,或 System.Collections.Generic 或 System.Collections.ComponentModel 提供的任何其他泛型类型。

于 2008-09-27T22:00:46.427 回答
-1

如果您必须使用 ArrayList 并且无法开始使用 List,并且您知道该 ArrayList 中每个元素的类型,您可以执行以下操作:

  string[] stringArray = myArrayList.ToArray(typeof(string)) as string[];

如果 myArrayList 中的某些内容不是字符串,在这种情况下,您将收到 InvalidCastException。

如果可以的话,我会开始使用提到的 OregonGhost 列表。

于 2008-09-27T22:08:44.443 回答