ArrayList

本文详细介绍了C#中的ArrayList用法,包括声明、元素类型、容量与数量、操作方法等,与数组的区别,以及与其他集合类型的比较,如[]、List、Array、ArrayList的区别与应用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

认识 C# 的 ArrayList

 

C# 中 List 用法

C# 不支持动态数组,用 ArrayList 可以实现动态数组的功能。

--------------------------------------------------------------------------------

ArrayList 的命名空间是 System.Collections。

 

ArrayList 元素类型

和数组不同,ArrayList的各个元素的类型可以不同。

 

声明对象

//声明 ArrayList 有三种重载方法,较常用的有两种

ArrayList al = new ArrayList();

ArrayList al = new ArrayList(3);

上例中,参数值 3 表示容量,即可以容纳多少个元素。

 

Capacity 与 Count

ArrayList 具有 Capacity 和 Count 属性,分别表示容量和数量。

Capacity 表示 ArrayList 可包含的元素数;Count 表示实际包含的元素数。

Capacity 可读可写;Count 只读。

当 Capacity 不够时

我们的 Capacity 如果小了,无法容纳我们实际的元素个数,这时再增加元素时:

如果指定了 Capacity,Capacity 将按指定的 Capacity 的倍数增长(如果 Capacity 小于 2,将按 2 的倍数增长),比如指定了Capacity 为 3,那么将按 3、6、9、12、15、18 ……线性的方式增长,直到可以容纳实际的元素个数。

如果没有指定Capacity 值,Capacity 将按 2、4、8、16、32、64 ……指数的方式增长,直到可以容纳实际的元素个数。

Capacity 不会自动缩小

当 Capacity 被自动增大后,即使删除了某些元素,Capacity 也不会自动缩小,需要设置 Capacity 来缩小,注意 Capacity 不能小于当前 Count。

 

 

C# 的 ArrayList

C# 不支持动态数组,用 ArrayList 可以实现动态数组的功能。


ArrayList 的名称空间是 System.Collections。

ArrayList 元素类型

和数组不同,ArrayList 的各个元素的类型可以不同。

声明对象

//声明 ArrayList 有三种重载方法,较常用的有两种
ArrayList al = new ArrayList();
ArrayList al = new ArrayList(3);

上例中,参数值 3 表示容量,即可以容纳多少个元素。


ArrayList对象就是一个可变长的数组,可以根据需要添加元素.使用ArrayList的方法可以向数组列表中添加元素,或取出,修改某个元素.

如:

ArrayList MyArrayList = newArrayList();

MyArrayList.add("Caoxi");

MyArrayList.Clear();

ArrayList中取出的对象都是object类型,使用前要将其转换成合适的类型.

ArrayList theArrayList = newArrayList();

theArrayList.Add("1");

theArrayList.Add("2");

string s =(string)theArrayList[0];

string s1 =(string)theArrayList[1];

注意Contains()方法       如果ArrayList中包含参数提供的对象,则返回true,否则返回false

if(theArrayList.Contains("1"))     //判断字符"1"是否存在于ArrayList  

 

 

C# []、List、Array、ArrayList 区别及应用

[] 是针对特定类型、固定长度的。

List 是针对特定类型、任意长度的。

Array是针对任意类型、固定长度的。

ArrayList 是针对任意类型、任意长度的。

Array和 ArrayList 是通过存储object 实现任意类型的,所以使用时要转换。

应用示例

usingSystem;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

public partial class_Default : System.Web.UI.Page
{
    protected void Page_Load(objectsender, EventArgs e)
    {
        // System.Int32 是结构
        int[]arr = new int[] { 1, 2, 3 };
        Response.Write(arr[0]); // 1
        Change(arr);
        Response.Write(arr[0]); // 2

        // List 的命名空间是System.Collections.Generic
        List<int>list = new List<int>();
        list.Add(1);
        list.Add(2);
        list.Add(3);
        Response.Write(list[0]); // 1
        Change(list);
        Response.Write(list[0]); // 2

        // Array 的命名空间是System
        Array array =Array.CreateInstance(System.Type.GetType("System.Int32"),3); // Array 是抽象类,不能使用 new Array 创建。
        array.SetValue(1, 0);
        array.SetValue(2, 1);
        array.SetValue(3, 2);
        Response.Write(array.GetValue(0));// 1
        Change(array);
        Response.Write(array.GetValue(0));// 2

        // ArrayList 的命名空间是System.Collections
        ArrayList arrayList = newArrayList(3);
        arrayList.Add(1);
        arrayList.Add(2);
        arrayList.Add(3);
        Response.Write(arrayList[0]); // 1
        Change(arrayList);
        Response.Write(arrayList[0]); // 2
    }

    private void Change(int[]arr)
    {
        for (int i =0; i < arr.Length; i++)
        {
            arr[i]*= 2;
        }
    }

    private void Change(List<int>list)
    {
        for (int i =0; i < list.Count; i++) // 使用 Count
        {
            list[i]*= 2;
        }
    }


    private void Change(Arrayarray)
    {
        for (int i =0; i < array.Length; i++) // 使用 Length
        {
            array.SetValue((int)array.GetValue(i)* 2, i); // 需要类型转换
        }
    }

    private voidChange(ArrayList arrayList)
    {
        for (int i =0; i < arrayList.Count; i++) // 使用 Count
        {
            arrayList[i]= (int)arrayList[i] * 2; // 需要类型转换
        }
    }
}

 

 

C#.net ArrayList用法

System.Collections.ArrayList类是一个特殊的数组。通过添加和删除元素,就可以动态改变数组的长度。

一.优点

1。支持自动改变大小的功能
2。可以灵活的插入元素
3。可以灵活的删除元素

二.局限性

跟一般的数组比起来,速度上差些

三.添加元素

1.publicvirtualintAdd(objectvalue);

将对象添加到ArrayList的结尾处

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
内容为abcde

2.publicvirtualvoidInsert(intindex,objectvalue);

将元素插入ArrayList的指定索引处

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Insert(0,"aa");

结果为aaabcde

3.publicvirtualvoidInsertRange(intindex,ICollectionc);

将集合中的某个元素插入ArrayList的指定索引处

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
ArrayListlist2=newArrayList();
list2.Add("tt");
list2.Add("ttt");
aList.InsertRange(2,list2);

结果为abtttttcde

四.删除

a)publicvirtualvoidRemove(objectobj);

从ArrayList中移除特定对象的第一个匹配项,注意是第一个

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Remove("a");

结果为bcde

2.publicvirtualvoidRemoveAt(intindex);

移除ArrayList的指定索引处的元素

aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveAt(0);

结果为bcde

3.publicvirtualvoidRemoveRange(intindex,intcount);

从ArrayList中移除一定范围的元素。Index表示索引,count表示从索引处开始的数目

aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.RemoveRange(1,3);

结果为ae

4.publicvirtualvoidClear();

从ArrayList中移除所有元素。

五.排序

a)publicvirtualvoidSort();

对ArrayList或它的一部分中的元素进行排序。

ArrayListaList=newArrayList();
aList.Add("e");
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();

结果为eabcd

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Sort();//排序
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();

结果为abcde

b)publicvirtualvoidReverse();

将ArrayList或它的一部分中元素的顺序反转。

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
aList.Reverse();//反转
DropDownList1.DataSource=aList;//DropDownListDropDownList1;
DropDownList1.DataBind();
结果为edcba

六.查找

a)publicvirtualintIndexOf(object);
b)publicvirtualintIndexOf(object,int);
c)publicvirtualintIndexOf(object,int,int);

返回ArrayList或它的一部分中某个值的第一个匹配项的从零开始的索引。没找到返回-1。

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");
intnIndex=aList.IndexOf(“a”);//1
nIndex=aList.IndexOf(“p”);//没找到,-1
d)publicvirtualintLastIndexOf(object);
e)publicvirtualintLastIndexOf(object,int);
f)publicvirtualintLastIndexOf(object,int,int);

返回ArrayList或它的一部分中某个值的最后一个匹配项的从零开始的索引。

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("a");//同0
aList.Add("d");
aList.Add("e");
intnIndex=aList.LastIndexOf("a");//值为2而不是0

g)publicvirtualboolContains(objectitem);

确定某个元素是否在ArrayList中。包含返回true,否则返回false

七.其他

1.publicvirtualintCapacity{get;set;}

获取或设置ArrayList可包含的元素数。

2.publicvirtualintCount{get;}

获取ArrayList中实际包含的元素数。
Capacity是ArrayList可以存储的元素数。Count是ArrayList中实际包含的元素数。Capacity总是大于或等于Count。如果在添加元素时,Count超过Capacity,则该列表的容量会通过自动重新分配内部数组加倍。
如果Capacity的值显式设置,则内部数组也需要重新分配以容纳指定的容量。如果Capacity被显式设置为0,则公共语言运行库将其设置为默认容量。默认容量为16。
在调用Clear后,Count为0,而此时Capacity切是默认容量16,而不是0

3.publicvirtualvoidTrimToSize();

将容量设置为ArrayList中元素的实际数量。
如果不向列表中添加新元素,则此方法可用于最小化列表的内存系统开销。
若要完全清除列表中的所有元素,请在调用TrimToSize之前调用Clear方法。截去空ArrayList会将ArrayList的容量设置为默认容量,而不是零。

ArrayListaList=newArrayList();
aList.Add("a");
aList.Add("b");
aList.Add("c");
aList.Add("d");
aList.Add("e");//Count=5,Capacity=16,
aList.TrimToSize();//Count=Capacity=5;

 

 

 

C# Array和ArrayList,List区别

ASP.Net学习 2008-09-18 14:32:17 阅读4388 评论1   字号:大中小 订阅

一,C#array数组的用法范例:

type[]   typename=new type[size]; 

如int[] a=new int[2];string[] str=new string[5];

实事上我们平常是用int[],string[]...的,此时我们已经创建一个Array数组,只不过我们平常没有这种意识而已.

(1):type数据类型不能缺;且要统一,而不能是如 int[] a=new Array[];

(2):数组的大小size不能缺,否则c#认为是出错的,因为数组是一段固定长度的内存;

(3):右边是一个中括号[],而不是()

实例:


            //Array ar =new Array();//错误,无法创建抽象类或接口“System.Array”的实例
            //int[]array = new Array[3];错误,
            //int[]array = new Array[];错误,必须指定数组的大小或初始值
            //int[]array = new Array[3];//错误,无法转换为int[]
            //int[]array=new int[];//错误,必须指定数组的大小或初始值
            //平常我们int[],string[]...事实上就是声明一个array数组了


            int[] array= new int[5];
            //或int[] arr={1,2,3};
            for (int i =0; i < 5; i++)
            {
               array[i] = i*100;//注:array数组并不提供add,clear,addRange..方法,而是直接设置或获取值
               Response.Write(array[i] + "<br>");
            }
           Response.Write(array.Length + "<br><br>");

 

 int [] intarray=new int[9];
     intarray[0]=10;
     intarray[1]=20;
     intarray[2]=30;
     intarray[3]=40;
     intarray[4]=50;
     intarray[5]=60;
     intarray[6]=70;
     intarray[7]=80;
     intarray[8]=90;

二,C#ArrayList数组的用法范例:

 ArrayListal = new ArrayList();
           for (int i = 0; i < 3; i++)
           {
               al.Add(i);
               Response.Write(al[i].ToString() + "<br>");//
输出数组中的元素值
               // Response.Write(al[i]+ "<br>");
           }
           Response.Write(al.Count + "<br><br>");

           foreach (int obj in al)//或foreach(object obj in al),因为al是一个object类型的数组
           {
               Response.Write(obj+"-OK"+"<br>");
           }


三,ArrayList和Array相互之间的转化

         (1)以下是把ArrayList数组中的值拷贝到Array中去的实例用法

          //int[] IResult=newint[al.Count];
           //al.CopyTo(IResult);
            //或是用下面的方法
          int[] IResult =(int[])al.ToArray(typeof(Int32));//ToArray(Int32);这样错误,一定要强制类型转换
          //Person[]personArrayFromList = (Person[])personList.ToArray(typeof(Person));   

         foreach(intitem   in IResult)
            {
             Response.Write(item.ToString());
            }

 

Response.Write("以下是把Array数组中的值拷贝到ArrayList中去的实例用法" +"<br>" + "结果为:<br>");

            int[] a={ 222, 333, 555 };
            ArrayListarrList = new ArrayList();
            foreach(object obj in a)//或foreach (int obj in a)
            {
               arrList.Add(obj);
               Response.Write(obj+"<br>");
            }


### 在Unity中使用ArrayList或解决ArrayList相关问题 在Unity开发中,`ArrayList`是非泛型集合类的一部分,允许存储任意类型的元素。尽管C#推荐使用泛型集合(如`List<T>`),但在某些特定场景下,`ArrayList`仍然有其适用性[^4]。 #### 1. 创建和初始化ArrayList 创建一个`ArrayList`对象需要引入`System.Collections`命名空间。以下是一个简单的示例: ```csharp using System.Collections; public class ArrayListExample : MonoBehaviour { void Start() { // 创建一个新的ArrayList实例 ArrayList arrayList = new ArrayList(); // 添加不同类型的元素到ArrayList arrayList.Add("字符串"); arrayList.Add(123); arrayList.Add(45.67f); // 遍历并打印ArrayList中的所有元素 foreach (var item in arrayList) { Debug.Log(item); } } } ``` #### 2. 常见操作:添加、删除和访问元素 `ArrayList`提供了多种方法来操作其中的元素,包括但不限于`Add`、`Remove`、`Insert`和`Contains`等[^4]。 - **添加元素**:使用`Add`方法将新元素追加到集合末尾。 - **插入元素**:使用`Insert`方法在指定索引位置插入新元素。 - **删除元素**:使用`Remove`方法按值删除元素,或使用`RemoveAt`方法按索引删除。 - **查找元素**:使用`Contains`方法检查某个值是否存在于集合中。 以下代码展示了这些操作的具体用法: ```csharp void ExampleOperations() { ArrayList arrayList = new ArrayList { "A", "B", "C" }; // 插入元素 arrayList.Insert(1, "X"); // 删除元素 arrayList.Remove("B"); // 检查元素是否存在 if (arrayList.Contains("X")) { Debug.Log("元素X存在!"); } // 清空整个ArrayList arrayList.Clear(); } ``` #### 3. 解决常见问题 ##### (1) 类型安全问题 由于`ArrayList`是非泛型集合,它会将所有类型视为`Object`处理,这可能导致运行时类型不匹配的问题[^3]。为避免此类问题,建议在访问元素时显式转换类型: ```csharp object element = arrayList[0]; if (element is string str) { Debug.Log(str); } else { Debug.LogError("类型不匹配!"); } ``` ##### (2) 性能问题 当`ArrayList`存储值类型(如`int`或`float`)时,每次添加都会发生装箱操作,而每次访问都会发生拆箱操作,这会导致性能开销[^3]。如果性能是关键因素,推荐使用泛型集合`List<T>`替代`ArrayList`。 #### 4. 替代方案:使用泛型集合`List<T>` 虽然`ArrayList`功能强大,但现代C#开发中更推荐使用泛型集合`List<T>`,因为它提供了更好的类型安全性、更高的性能以及更丰富的API支持[^5]。 以下是一个使用`List<T>`的简单示例: ```csharp using System.Collections.Generic; public class ListExample : MonoBehaviour { void Start() { // 创建一个存储字符串的List List<string> list = new List<string>(); // 添加元素 list.Add("Unity"); list.Add("C#"); // 访问元素 Debug.Log(list[0]); // 遍历列表 foreach (var item in list) { Debug.Log(item); } } } ``` #### 5. 实际应用案例 假设需要动态管理一组游戏对象,可以使用`ArrayList`实现如下功能: ```csharp public class GameObjectManager : MonoBehaviour { private ArrayList gameObjects = new ArrayList(); public void AddGameObject(GameObject obj) { gameObjects.Add(obj); } public void RemoveGameObject(GameObject obj) { gameObjects.Remove(obj); } public void ClearAll() { gameObjects.Clear(); } public void PrintAll() { foreach (var obj in gameObjects) { if (obj is GameObject go) { Debug.Log(go.name); } } } } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值