如何resizeC#数组长度
来源:互联网 发布:惠普打印机是什么端口 编辑:程序博客网 时间:2024/04/29 00:12
表示今天被一个问题困惑到了。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.ArrayListinstead of a native array. Another (faster) solution is to re-allocate the arraywith a different size and to copy the contents of the old array to the newarray. 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]); }
- 如何resizeC#数组长度
- 如何获得数组的长度
- 如何获取数组的长度
- 如何获取数组的长度
- java如何增加数组长度
- C/C++ 中如何获取数组长度
- C/C++ 中如何获取数组长度
- C/C++ 中如何获取数组长度
- VBScript:如何获取数组实际长度
- c/c++如何获取数组的长度
- 如何获取一个数组的长度
- /C++中如何获取数组的长度?
- c/c++如何获得数组的长度
- delete [] 时如何知道数组长度
- C/C++中如何获取数组长度
- 如何获得一个数组的长度
- 如何创建一个不确定长度的数组
- 如何测量记录动态数组长度
- Javascript格式化工具
- win7下安装SQL2005EXPRESS出现29506错误码的解决方案
- 如何在控件上添加右键菜单
- NetCDF入门
- IHS静默安装
- 如何resizeC#数组长度
- 让Delphi的DataSnap发挥最大效率
- ASP.NET的身份验证
- 利用jsoncpp将json字符串转换为Vector
- WINCE6.0 中文支持
- 用ProxyFactoryBean创建AOP代理(转)
- Delphi2010 DataSnap入门 (一)
- Global.ascx详解
- 非阻塞提示框