Array.Resize 泛型方法-----将数组的大小更改为指定的新大小。
今天没事翻翻书,无意中看见了这个方法,我还以为数组的大小是不可改变的,定义多大就多大。今天才发现可以改变大小。
MSDN上面的解释是:
此方法分配一个具有指定大小的新数组,将元素从旧数组复制到新数组,然后用新数组替换旧数组。
如果 array 为空引用(在 Visual Basic 中为 Nothing),此方法将新建具有指定大小的数组。
如果 newSize 大于旧数组的 Length,则分配一个新数组,并将所有元素从旧数组复制到新数组。如果 newSize 小于旧数组的 Length,则分配一个新数组,并将元素从旧数组复制到新数组直到新数组被填满为止;旧数组中的剩余元素将被忽略。如果 newSize 与旧数组的 Length 相等,则此方法不执行任何操作。
此方法为 O(n) 操作,其中 n 是 newSize。
没事写了个测试程序:
这个方法最好少用,它会开辟新的内存并有一个复制的过程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestResize
{
class Program
{
static void Main(string[] args)
{
string[] strs = {
"one","two","three","four"
};
Console.WriteLine("The old array index and value:");
PrintIndexAndValues(strs);
Array.Resize(ref strs, 5);
Console.WriteLine("Resize to 5,The new array index and value:");
PrintIndexAndValues(strs);
Array.Resize(ref strs, 1);
Console.WriteLine("Resize to 1,The new array index and value:");
PrintIndexAndValues(strs);
string[] str=null;
Array.Resize(ref str, 1);
Console.WriteLine("Resize to 1,The new array index and value:");
PrintIndexAndValues(str);
Console.ReadLine();
}
public static void PrintIndexAndValues(string[] myArr)
{
for (int i = 0; i < myArr.Length; i++)
{
Console.WriteLine(" [{0}] : {1}", i, myArr[i]);
}
Console.WriteLine();
}
}
}
