C#入门7.9——ArrayList类中元素的添加

来源:互联网 发布:乐视mac 编辑:程序博客网 时间:2024/04/29 21:47

前面讲到数组一旦给定大小就是固定的了,不能再改。还有一种数组是可以扩充的,即ArrayList类,被称为动态数组或者集合。

使用步骤:

1.引入命名空间System.Collections;

2.创建实例。

3.引用对应的属性或方法。


实例:创建ArrayList实例myArrayList,使其固定大小为5,通过Add方法对其添加5个元素,再通过AddRange方法对其添加一个数组,然后遍历所有数组元素。

using System;using System.Collections.Generic;using System.Linq;using System.Text;//引用命名空间using System.Threading.Tasks;using System.Collections;namespace ConsoleApplication4{    class Program    {        static void Main(string[] args)        {            ArrayList myArrayList = new ArrayList(5);            //ArrayList的好处是,长度不固定,类型随意            //数组的长度是固定的,不能更改的,类型单一,只能为其中一种            Console.WriteLine("myArrayList初始化之后有{0}个元素",myArrayList.Count);            //Add方法用于向ArrayList中添加单个元素,每次只能加一个            myArrayList.Add(123);            myArrayList.Add('a');            myArrayList.Add("myString");            myArrayList.Add(25.6);            myArrayList.Add(10L);//长整型数L            Console.WriteLine("使用Add方法添加5个元素之后,有{0}个元素",myArrayList.Count);            //Addrange方法用于一次性向ArrayList中添加多个元素,可以是一个数组            string[] mystringArray = {"张三","李四","王五","老六"};            myArrayList.AddRange(mystringArray);            Console.WriteLine("使用AddRange方法后,有{0}个元素",myArrayList.Count);            //遍历集合元素            //引用类型string object类是所有类型的基类            foreach (object outElement in myArrayList) Console.WriteLine(outElement+"\t");            Console.WriteLine();            Console.ReadKey();        }    }}

ArrayList类的属性

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

Count 获取ArrayList实际包含的元素数

IsFixedSize 获取一个值,该值指示ArrayList是否具有固定大小

IsReadOnly 获取一个值,该值指示ArrayList是否为只读

Item 获取或设置指定索引处的元素

0 0
原创粉丝点击