非范型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);

    // 遍历 ArrayList
    foreach(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,因此不需要进行类型转换,代码更简洁、更安全。

相关推荐
__water2 小时前
『功能项目』回调函数处理死亡【54】
c#·回调函数·unity引擎
__water2 小时前
『功能项目』眩晕图标显示【52】
c#·unity引擎·动画事件
__water3 小时前
『功能项目』第二职业法师的平A【57】
c#·unity引擎·魔法球伤害传递
__water5 小时前
『功能项目』战士的伤害型技能【45】
c#·unity引擎·战士职业伤害型技能
君莫愁。6 小时前
【Unity】检测鼠标点击位置是否有2D对象
unity·c#·游戏引擎
Lingbug7 小时前
.Net日志组件之NLog的使用和配置
后端·c#·.net·.netcore
咩咩觉主7 小时前
Unity实战案例全解析:PVZ 植物卡片状态分析
unity·c#·游戏引擎
Echo_Lee07 小时前
C#与Python脚本使用共享内存通信
开发语言·python·c#
__water14 小时前
『功能项目』QFrameWork框架重构OnGUI【63】
c#·unity引擎·重构背包框架
Crazy Struggle14 小时前
C# + WPF 音频播放器 界面优雅,体验良好
c#·wpf·音频播放器·本地播放器