Array.Resize(T [],Int32)方法用于调整数组中存在的元素的大小。换句话说,此方法用于将一维数组的元素数更改为指定的新大小。它仅调整一维数组的大小,而不调整多维数组的大小。
句法:
public static void Resize (ref T[] array, int newSize);
参数:
array: It is a one-dimensional, zero-based array to resize, or null to create a new array with the specified size.
newsize: It is the size of the new array.
异常:如果nsize的值小于零,则此方法将提供ArgumentOutOfRangeException 。
注意:此方法是O(n)运算,其中n是新大小。
下面给出了一些示例,以更好地理解实现:
范例1:
// C# program to resize the
// elements of the 1-D array
using System;
public class GFG {
// Main method
static public void Main()
{
// create and initialize array
string[] myarray = {"C#", "Java", "C++", "Python",
"HTML", "CSS", "JavaScript"};
// Display original array before Resize
Console.WriteLine("Original Array:");
foreach(string i in myarray)
{
Console.WriteLine(i);
}
int len = myarray.Length;
Console.WriteLine("Length of myarray: "+len);
Console.WriteLine();
// Resize the element of myarray and
// create a new array. Here new array
// is smaller than the original array
// so, elements are copied from the
// myarray to the new array until the
// new one is filled. The rest of the
// elements in the old array are ignored
Array.Resize(ref myarray, len - 3);
Console.WriteLine("New array is less than myarray:");
foreach(string j in myarray)
{
Console.WriteLine(j);
}
}
}
输出:
Original Array:
C#
Java
C++
Python
HTML
CSS
JavaScript
Length of myarray: 7
New array is less than myarray:
C#
Java
C++
Python
范例2:
// C# program to resize the
// elements of the 1-D array
using System;
public class GFG {
// Main method
static public void Main()
{
// create and initialize array
string[] myarray = {"C#", "C++", "Ruby",
"Java", "PHP", "Perl"};
// Display original string before Resize
Console.WriteLine("Original Array:");
foreach(string i in myarray)
{
Console.WriteLine(i);
}
// Length of old array
int len = myarray.Length;
Console.WriteLine("Length of myarray: "+len);
Console.WriteLine();
// Resize the element of myarray
// and create a new array
// Here new array is greater than
// original array so, all the element
// from myarray is copied to new array
// and remaining will be null
Array.Resize(ref myarray, 10);
Console.WriteLine("New array is greater than myarray:");
foreach(string j in myarray)
{
Console.WriteLine(j);
}
// Length of new array
int len1 = myarray.Length;
Console.WriteLine("Length of New Array: "+len1);
}
}
输出:
Original Array:
C#
C++
Ruby
Java
PHP
Perl
Length of myarray: 6
New array is greater than myarray:
C#
C++
Ruby
Java
PHP
Perl
Length of New Array: 10
参考: https://docs.microsoft.com/zh-cn/dotnet/api/system.array.resize?view=netcore-2.1