Array.Resize<T>(T[], Int32) Метод

Определение

Изменяет количество элементов в одномерном массиве до указанной величины.

public:
generic <typename T>
 static void Resize(cli::array <T> ^ % array, int newSize);
public static void Resize<T> (ref T[] array, int newSize);
public static void Resize<T> (ref T[]? array, int newSize);
static member Resize : T[] * int -> unit
Public Shared Sub Resize(Of T) (ByRef array As T(), newSize As Integer)

Параметры типа

T

Тип элементов массива.

Параметры

array
T[]

Подлежащий изменению размера одномерный массив, индексация которого начинается с нуля, или значение null для создания нового массива заданного размера.

newSize
Int32

Размер нового массива.

Исключения

Значение параметра newSize меньше нуля.

Примеры

В следующем примере показано, как изменение размера влияет на массив.

using namespace System;
static void PrintIndexAndValues(array<String^>^myArr)
{
    for(int i = 0; i < myArr->Length; i++)
    {
       Console::WriteLine(L"   [{0}] : {1}", i, myArr[i]);
    }
    Console::WriteLine();
}

int main()
{
   
    // Create and initialize a new string array.
    array<String^>^myArr = {L"The", L"quick", L"brown", L"fox",
        L"jumps", L"over", L"the", L"lazy", L"dog"};
   
    // Display the values of the array.
    Console::WriteLine( 
        L"The string array initially contains the following values:");
    PrintIndexAndValues(myArr);
   
    // Resize the array to a bigger size (five elements larger).
    Array::Resize(myArr, myArr->Length + 5);
   
    // Display the values of the array.
    Console::WriteLine(L"After resizing to a larger size, ");
    Console::WriteLine(L"the string array contains the following values:");
    PrintIndexAndValues(myArr);
   
    // Resize the array to a smaller size (four elements).
    Array::Resize(myArr, 4);
   
    // Display the values of the array.
    Console::WriteLine(L"After resizing to a smaller size, ");
    Console::WriteLine(L"the string array contains the following values:");
    PrintIndexAndValues(myArr);
    return 1;
}

/* 
This code produces the following output.

The string array initially contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After resizing to a larger size, 
the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog
   [9] :
   [10] :
   [11] :
   [12] :
   [13] :

After resizing to a smaller size, 
the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox

*/
using System;

public class SamplesArray
{
    public static void Main()  {

        // Create and initialize a new string array.
        String[] myArr = {"The", "quick", "brown", "fox", "jumps",
            "over", "the", "lazy", "dog"};

        // Display the values of the array.
        Console.WriteLine(
            "The string array initially contains the following values:");
        PrintIndexAndValues(myArr);

        // Resize the array to a bigger size (five elements larger).
        Array.Resize(ref myArr, myArr.Length + 5);

        // Display the values of the array.
        Console.WriteLine("After resizing to a larger size, ");
        Console.WriteLine("the string array contains the following values:");
        PrintIndexAndValues(myArr);

        // Resize the array to a smaller size (four elements).
        Array.Resize(ref myArr, 4);

        // Display the values of the array.
        Console.WriteLine("After resizing to a smaller size, ");
        Console.WriteLine("the string array contains the following values:");
        PrintIndexAndValues(myArr);
    }

    public static void PrintIndexAndValues(String[] myArr)  {
        for(int i = 0; i < myArr.Length; i++)
        {
            Console.WriteLine("   [{0}] : {1}", i, myArr[i]);
        }
        Console.WriteLine();
    }
}

/*
This code produces the following output.

The string array initially contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After resizing to a larger size,
the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog
   [9] :
   [10] :
   [11] :
   [12] :
   [13] :

After resizing to a smaller size,
the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox

*/
open System

let printIndexAndValues (myArr: string []) =
    for i = 0 to myArr.Length - 1 do
        printfn $"   [{i}] : {myArr[i]}"
    printfn ""

// Create and initialize a new string array.
let mutable myArr = 
    [| "The"; "quick"; "brown"; "fox"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Display the values of the array.
printfn "The string array initially contains the following values:"
printIndexAndValues myArr

// Resize the array to a bigger size (five elements larger).
Array.Resize(&myArr, myArr.Length + 5)

// Display the values of the array.
printfn "After resizing to a larger size, "
printfn "the string array contains the following values:"
printIndexAndValues myArr

// Resize the array to a smaller size (four elements).
Array.Resize(&myArr, 4)

// Display the values of the array.
printfn "After resizing to a smaller size, "
printfn "the string array contains the following values:"
printIndexAndValues myArr


(*
This code produces the following output.

The string array initially contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After resizing to a larger size,
the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog
   [9] :
   [10] :
   [11] :
   [12] :
   [13] :

After resizing to a smaller size,
the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox

*)
Public Class SamplesArray

    Public Shared Sub Main()

        ' Create and initialize a new string array.
        Dim myArr As String() =  {"The", "quick", "brown", "fox", _
            "jumps", "over", "the", "lazy", "dog"}

        ' Display the values of the array.
        Console.WriteLine( _
            "The string array initially contains the following values:")
        PrintIndexAndValues(myArr)

        ' Resize the array to a bigger size (five elements larger).
        Array.Resize(myArr, myArr.Length + 5)

        ' Display the values of the array.
        Console.WriteLine("After resizing to a larger size, ")
        Console.WriteLine("the string array contains the following values:")
        PrintIndexAndValues(myArr)

        ' Resize the array to a smaller size (four elements).
        Array.Resize(myArr, 4)

        ' Display the values of the array.
        Console.WriteLine("After resizing to a smaller size, ")
        Console.WriteLine("the string array contains the following values:")
        PrintIndexAndValues(myArr)

    End Sub

    Public Shared Sub PrintIndexAndValues(myArr() As String)
        Dim i As Integer
        For i = 0 To myArr.Length - 1
            Console.WriteLine("   [{0}] : {1}", i, myArr(i))
        Next i
        Console.WriteLine()
    End Sub

End Class

'This code produces the following output.
'
'The string array initially contains the following values:
'   [0] : The
'   [1] : quick
'   [2] : brown
'   [3] : fox
'   [4] : jumps
'   [5] : over
'   [6] : the
'   [7] : lazy
'   [8] : dog
'
'After resizing to a larger size, 
'the string array contains the following values:
'   [0] : The
'   [1] : quick
'   [2] : brown
'   [3] : fox
'   [4] : jumps
'   [5] : over
'   [6] : the
'   [7] : lazy
'   [8] : dog
'   [9] :
'   [10] :
'   [11] :
'   [12] :
'   [13] :
'
'After resizing to a smaller size, 
'the string array contains the following values:
'   [0] : The
'   [1] : quick
'   [2] : brown
'   [3] : fox

Комментарии

Этот метод выделяет новый массив с указанным размером, копирует элементы из старого массива в новый, а затем заменяет старый массив новым. array должен быть одномерным массивом.

Если array это так null, этот метод создает новый массив с указанным размером.

Если newSize больше Length старого массива, выделяется новый массив, а все элементы копируются из старого массива в новый. Если newSize значение меньше Length старого массива, выделяется новый массив, а элементы копируются из старого массива в новый, пока не будет заполнен новый массив. Остальные элементы старого массива игнорируются. Если newSize он равен Length старому массиву, этот метод ничего не делает.

Этот метод представляет собой операцию O(n), где n находится newSize.

Метод Resize изменяет размер только одномерного массива. Класс Array не включает метод изменения размера многомерных массивов. Для этого необходимо предоставить собственный код или вызвать специальный метод в сторонней библиотеке. Следующий код иллюстрирует одну возможную реализацию метода, который изменяет размер массива n измерений.

using System;

public class Example
{
   public static void Main()
   {
      int[,] arr = new int[10,2];
      for (int n1 = 0; n1 <= arr.GetUpperBound(0); n1++) {
         arr[n1, 0] = n1;
         arr[n1, 1] = n1 * 2;
      }

      // Make a 2-D array larger in the first dimension.
      arr = (int[,]) ResizeArray(arr, new int[] { 12, 2} );
      for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++)
         Console.WriteLine("{0}: {1}, {2}", ctr, arr[ctr, 0], arr[ctr, 1]);
      Console.WriteLine();

      // Make a 2-D array smaller in the first dimension.
      arr = (int[,]) ResizeArray(arr, new int[] { 2, 2} );
      for (int ctr = 0; ctr <= arr.GetUpperBound(0); ctr++)
         Console.WriteLine("{0}: {1}, {2}", ctr, arr[ctr, 0], arr[ctr, 1]);
   }

   private static Array ResizeArray(Array arr, int[] newSizes)
   {
      if (newSizes.Length != arr.Rank)
         throw new ArgumentException("arr must have the same number of dimensions " +
                                     "as there are elements in newSizes", "newSizes");

      var temp = Array.CreateInstance(arr.GetType().GetElementType(), newSizes);
      int length = arr.Length <= temp.Length ? arr.Length : temp.Length;
      Array.ConstrainedCopy(arr, 0, temp, 0, length);
      return temp;
   }
}
// The example displays the following output:
//       0: 0, 0
//       1: 1, 2
//       2: 2, 4
//       3: 3, 6
//       4: 4, 8
//       5: 5, 10
//       6: 6, 12
//       7: 7, 14
//       8: 8, 16
//       9: 9, 18
//       10: 0, 0
//       11: 0, 0
//
//       0: 0, 0
//       1: 1, 2
open System

let resizeArray (arr: Array) (newSizes: int []) =
    if newSizes.Length <> arr.Rank then
        invalidArg "newSizes" "arr must have the same number of dimensions as there are elements in newSizes"
    let temp = Array.CreateInstance(arr.GetType().GetElementType(), newSizes)
    let length = min arr.Length temp.Length
    Array.ConstrainedCopy(arr, 0, temp, 0, length)
    temp

[<EntryPoint>]
let main _ =
    let arr = Array2D.init 10 2 (fun x y -> if y = 0 then x else x * 2)

    // Make a 2-D array larger in the first dimension.
    let arr = resizeArray arr [| 12; 2 |]
    for i = 0 to arr.GetUpperBound 0 do
        printfn $"{i}: {arr.GetValue(i, 0)}, {arr.GetValue(i, 1)}"
    printfn ""

    // Make a 2-D array smaller in the first dimension.
    let arr = resizeArray arr [| 2; 2|]
    for i = 0 to arr.GetUpperBound 0 do
        printfn $"{i}: {arr.GetValue(i, 0)}, {arr.GetValue(i, 1)}"
    0

// The example displays the following output:
//       0: 0, 0
//       1: 1, 2
//       2: 2, 4
//       3: 3, 6
//       4: 4, 8
//       5: 5, 10
//       6: 6, 12
//       7: 7, 14
//       8: 8, 16
//       9: 9, 18
//       10: 0, 0
//       11: 0, 0
//
//       0: 0, 0
//       1: 1, 2
Module Example
   Public Sub Main()
      Dim arr(9, 1) As Integer
      For n1 As Integer = 0 To arr.GetUpperBound(0)
         arr(n1, 0) = n1
         arr(n1, 1) = n1 * 2
      Next 

      ' Make a 2-D array larger in the first dimension.
      arr = CType(ResizeArray(arr, { 12, 2} ), Integer(,))
      For ctr = 0 To arr.GetUpperBound(0)
         Console.WriteLine("{0}: {1}, {2}", ctr, arr(ctr, 0), arr(ctr, 1))
      Next
      Console.WriteLine()
      
      ' Make a 2-D array smaller in the first dimension.
      arr = CType(ResizeArray(arr, { 2, 2} ), Integer(,))
      For ctr = 0 To arr.GetUpperBound(0)
         Console.WriteLine("{0}: {1}, {2}", ctr, arr(ctr, 0), arr(ctr, 1))
      Next
   End Sub

   Private Function ResizeArray(arr As Array, newSizes() As Integer) As Array
      If newSizes.Length <> arr.Rank Then
         Throw New ArgumentException("arr must have the same number of dimensions " +
                                     "as there are elements in newSizes", "newSizes") 
      End If 

      Dim temp As Array = Array.CreateInstance(arr.GetType().GetElementType(), newSizes)
      Dim length As Integer = If(arr.Length <= temp.Length, arr.Length, temp.Length )
      Array.ConstrainedCopy(arr, 0, temp, 0, length)
      Return temp
   End Function
End Module
' The example displays the following output:
'       0: 0, 0
'       1: 1, 2
'       2: 2, 4
'       3: 3, 6
'       4: 4, 8
'       5: 5, 10
'       6: 6, 12
'       7: 7, 14
'       8: 8, 16
'       9: 9, 18
'       10: 0, 0
'       11: 0, 0
'       
'       0: 0, 0
'       1: 1, 2

Применяется к