指定ArrayList元素的类型

时间:2020-03-06 14:49:58  来源:igfitidea点击:

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

解决方案

我们可能正在寻找List <T>,它从.NET 2.0开始可用,或者是从System.Collections.Generic或者System.Collections.ComponentModel获得的任何其他通用类型。

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

using System.Collections.Generic;

var list = new List<int>();
list.Add(1);
list.Add("string"); //compile-time error!
int i = list[0];

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

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

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

如果可以的话,我将开始使用List作为OregonGhost提及。