欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 非范型ArrayList和泛型List<T>

非范型ArrayList和泛型List<T>

2024/10/24 23:28:25 来源:https://blog.csdn.net/weixin_38566632/article/details/141003117  浏览:    关键词:非范型ArrayList和泛型List<T>

ArrayList 是 C# 中的一个非泛型集合类,它属于 System.Collections 命名空间。它提供了动态数组的功能,允许你在运行时添加、删除和访问元素。然而,需要注意的是,ArrayList 并不是类型安全的,因为你可以向其中添加任何类型的对象,这可能会在后续处理元素时引发问题,比如类型转换错误。
创建 ArrayList
在 C# 中,你可以这样创建一个 ArrayList:
csharp
复制
using System;
using System.Collections;

class Program
{
static void Main()
{
ArrayList myArrayList = new ArrayList();

    // 添加元素myArrayList.Add(1);myArrayList.Add("Hello");myArrayList.Add(3.14);// 遍历 ArrayListforeach(object item in myArrayList){Console.WriteLine(item);}
}

}
在这个例子中,ArrayList 包含了不同类型的对象(int、string 和 double)。这展示了 ArrayList 的灵活性,但也揭示了它类型不安全的缺点。
访问元素
你可以通过索引访问 ArrayList 中的元素,但是需要注意,访问时返回的类型是 object,因此如果你知道元素的确切类型,可能需要进行类型转换:
csharp
复制
int firstItem = (int)myArrayList[0];
string secondItem = (string)myArrayList[1];
double thirdItem = (double)myArrayList[2];
添加和删除元素
除了 Add 方法,ArrayList 还提供了 AddRange 方法来一次性添加多个元素(这些元素应该来自实现了 ICollection 接口的集合),以及 Remove 和 RemoveAt 方法来删除元素。
泛型集合 vs ArrayList
尽管 ArrayList 提供了一种灵活的方式来存储对象集合,但在现代 C# 编程中,更推荐使用泛型集合(如 List),因为它们提供了类型安全,避免了类型转换的需要,并且通常提供了更好的性能。
例如,使用 List 代替 ArrayList 存储整数:
csharp
复制
using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
List myList = new List();

    myList.Add(1);myList.Add(2);myList.Add(3);// 不需要类型转换foreach(int item in myList){Console.WriteLine(item);}
}

}
在这个例子中,List 明确指定了其存储的元素类型为 int,因此不需要进行类型转换,代码更简洁、更安全。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com