给数组扩容的几种方式

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

 
 
    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;
 
 
            //给扩容后原数组的最后一个位置赋值
            arrs[arrs.Length - 1] = 6;
 
 
            foreach (var item in arrs)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
   
 

□ 使用Array的静态方法扩容

但是,拷贝来拷贝去显得比较繁琐,我们也可以使用Array.Resize()方法给数组扩容。

 
 
        static void Main(string[] args)
        {
            int[] arrs = new[] {1, 2, 3, 4, 5};
 
 
            Array.Resize(ref arrs, arrs.Length + 1);
 
 
            //给扩容后原数组的最后一个位置赋值
            arrs[arrs.Length - 1] = 6;
 
 
            foreach (var item in arrs)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();
        }
 
 

 

总结:数组扩容优先考虑使用Array的静态方法Resize,其次考虑把一个扩容的、临时的数组赋值给原数组。

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值