在C#中用new 出来的数组是固定的,有时候我们就要用到动态数组,怎么办呢?
不用怕,在C#中有一个ArrayList动态数组,可增加,删除,查询等。
那么我简单的介绍一下它的功能和操作:
在使用这个类时,大家要记住它的命名空间:"System.Collections"
using System; using System.Collections; public class SamplesArrayList
{
public static void Main() {
// 创建并添加数据ArrayList myAL = new ArrayList(); myAL.Add("Hello"); myAL.Add("World"); myAL.Add("!"); // Displays the properties and values of the ArrayList. Console.WriteLine( "myAL" );
//获取数组中的个数
Console.WriteLine( " Count: {0}", myAL.Count ); //获取数组的空间大小(可包含的元素个数)
Console.WriteLine( " Capacity: {0}", myAL.Capacity );
Console.Write( " Values:" );
PrintValues( myAL );myAL.Clear(); //清空数组 }
//循环读取数据 public static void PrintValues( IEnumerable myList )
{
foreach ( Object obj in myList )
Console.Write( " {0}", obj );
Console.WriteLine();
}
}
/*
This code produces output similar to the following:
myAL
Count: 3
Capacity: f
Values: Hello World !
*/