c#里的动态数组ArrayList

很多人都碰到这样的问题,就是在c#里面定义动态数组并不像javascript那样随意,只能定义定长的数组,或者必须要对数组长度赋值,但是我知道ArrayList是可以添加任意长度的,而且可以转换成任意的类型数组,所以我使用了ArrayList进行转换,不知道大家有没有其他方法希望不吝赐教。

我的方法:  


ArrayList list = new ArrayList();
list.Add(
"aaa");
list.Add(
"bbb");

string[] caption = (string[])list.ToArray(typeof(string));

忘了说明了,ArrayList需要引用的命名空间为:using System.Collections;

关于ArrayList的使用可以看下面的例子:


  ArrayList al = new ArrayList();
            al.Add(
100);//单个添加
            foreach (int number in new int[6] { 937248 })
            {
                al.Add(number);
//集体添加方法一
            }
            
int[] number2 = new int[2] { 1112 };
            al.AddRange(number2);
//集体添加方法二
            al.Remove(3);//移除值为3的
            al.RemoveAt(3);//移除第3个
            ArrayList al2 = new ArrayList(al.GetRange(13));//新ArrayList只取旧ArrayList一部份


            Console.WriteLine(
"遍历方法一:");
            
foreach (int i in al)//不要强制转换
            {
                Console.WriteLine(i);
//遍历方法一
            }

            Console.WriteLine(
"遍历方法二:");
            
for (int i = 0; i < al2.Count; i++)//数组是length
            {
                
int number = (int)al2[i];//一定要强制转换
                Console.WriteLine(number);//遍历方法二

            }
原文地址:https://www.cnblogs.com/hackpig/p/1668359.html