给数组扩容的几种方式

王朝学院·作者佚名  2016-05-17
窄屏简体版  字體: 小  |  中  |  大  |  超大  

给数组扩容的几种方式假设有一个规定长度的数组,如何扩容呢?最容易想到的是通过如下方式扩容:

class PRogram

{

static void Main(string[] args)

{

int[] arrs = new[] {1, 2, 3, 4, 5};

arrs[5] = 6;

}

}

报错:未处理IndexOutOfRanageException,索引超出了数组界限。

□ 创建一个扩容的临时数组,然后赋值给原数组,使用循环遍历方式

static void Main(string[] args)

{

int[] arrs = new[] {1, 2, 3, 4, 5};

int[] temp = new int[arrs.Length + 1];

//遍历arrs数组,把该数组的元素全部赋值给temp数组

for (int i = 0; i < arrs.Length; i++)

{

temp[i] = arrs[i];

}

//把临时数组赋值给原数组,这时原数组已经扩容

arrs = temp;

//给扩容后原数组的最后一个位置赋值

arrs[arrs.Length - 1] = 6;

foreach (var item in arrs)

{

Console.WriteLine(item);

}

Console.ReadKey();

}

□ 创建一个扩容的临时数组,然后赋值给原数组,使用Array的静态方法

像这种平常的数组间的拷贝,Array类肯定为我们准备了静态方法:Array.Copy()。

static void Main(string[] args)

{

int[] arrs = new[] {1, 2, 3, 4, 5};

int[] temp = new int[arrs.Length + 1];

Array.Copy(arrs, temp, arrs.Length);

//把临时数组赋值给原数组,这时原数组已经扩容

arrs = temp;

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航