如何resizeC#数组长度

表示今天被一个问题困惑到了。C#中数组的Length的大小到底是数组申请内存大小还是实际存储的元素长度。我们可以

int[] a = new int[10];

a[0]=1;

a[1]=2;

a[2]=3;  //但是我只初始化前三个元素

如果在保留数组中原有的内容的基础上,怎么设置一个Resize(int[] arr, int newsize)方法,供我们调节(增大或减小)数组长度。

这样我还能用a.Length吗?

在网上找到一个resize的代码~是用Length的~ 

先记着这个问题,自己下去再试试吧~

转自http://www.source-code.biz/snippets/csharp/1.htm

How to resize an array in C#

In C#, arrays cannot be resized dynamically. One approach is to use System.Collections.ArrayList instead of a native array. Another (faster) solution is to re-allocate the array with a different size and to copy the contents of the old array to the new array. The generic function resizeArray (below) can be used to do that.


 

// Reallocates an array with a new size, and copies the contents
// of the old array to the new array.
// Arguments:
//   oldArray  the old array, to be reallocated.
//   newSize   the new array size.
// Returns     A new array with the same contents.
public static System.Array ResizeArray (System.Array oldArray, int newSize) {
   int oldSize = oldArray.Length;
   System.Type elementType = oldArray.GetType().GetElementType();
   System.Array newArray = System.Array.CreateInstance(elementType,newSize);
   int preserveLength = System.Math.Min(oldSize,newSize);
   if (preserveLength > 0)
      System.Array.Copy (oldArray,newArray,preserveLength);
   return newArray; }

 


 

// Test routine for ResizeArray().
public static void Main () {
   int[] a = {1,2,3};
   a = (int[])ResizeArray(a,5);
   a[3] = 4;
   a[4] = 5;
   for (int i=0; i<a.Length; i++)
      System.Console.WriteLine (a[i]); }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值