C# | Método Array.ConstrainedCopy() – Part 1

Este método se utiliza para copiar un rango de elementos de un Array que comienza en el índice de origen especificado y los pega en otro Array que comienza en el índice de destino especificado. Garantiza que todos los cambios se deshacen si la copia no se realiza correctamente.

Sintaxis:

public static void ConstrainedCopy (Array sourceArray, int sourceIndex, 
Array destinationArray, int destinationIndex, int length);

Parámetros:

sourceArray: Es el Array que contiene los datos a copiar.
sourceIndex: Es el entero de 32 bits que representa el índice en sourceArray en el que comienza la copia.
DestinationArray: Es el Array que recibe los datos.
DestinationIndex: es el entero de 32 bits que representa el índice en DestinationArray en el que comienza el almacenamiento.
longitud: Es el entero de 32 bits que representa el número de elementos a copiar.

Excepciones:

  • ArgumentNullException: si sourceArray o destinationArray es nulo.
  • RankException: si sourceArray y destinationArray tienen rangos diferentes.
  • ArrayTypeMismatchException: si el tipo sourceArray no es el mismo que el tipo DestinationArray ni se deriva del mismo.
  • InvalidCastException: al menos un elemento en sourceArray no se puede convertir al tipo de destinationArray.
  • ArgumentOutOfRangeException: si sourceIndex es menor que el límite inferior de la primera dimensión de sourceArray o destinationIndex es menor que el límite inferior de la primera dimensión de destinationArray o la longitud es menor que cero.
  • ArgumentException: si la longitud es mayor que la cantidad de elementos desde sourceIndex hasta el final de sourceArray O la longitud es mayor que la cantidad de elementos desde DestinationIndex hasta el final de destinationArray.

Los siguientes programas ilustran el uso del método Array.ConstrainedCopy(Array, Int32, Array, Int32, Int32):

Ejemplo 1:

// C# program to demonstrate
// ConstrainedCopy() method
using System;
using System.Collections.Generic;
  
public class GFG {
  
    // Main Method
    public static void Main()
    {
  
        try {
  
            // Creating and initializing new the String
            String[] srcArr = { "Sun", "Mon", "Tue", "Thu" };
  
            // Creating the object of empty String Array
            String[] destArr = new String[10];
  
            // Display the values of the myArr.
            Console.WriteLine("Initial Array:");
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(srcArr);
  
            // getting a ConstrainedCopy in destArr
            // from srcArr using method ConstrainedCopy()
            Array.ConstrainedCopy(srcArr, 1, destArr, 0, 3);
  
            // Display the value of the destArr
            Console.WriteLine("Destination Array: ");
  
            // calling the PrintIndexAndValues()
            // method to print
            PrintIndexAndValues(destArr);
        }
        catch (ArgumentNullException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (RankException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (ArrayTypeMismatchException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (InvalidCastException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (ArgumentOutOfRangeException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
        catch (ArgumentException e) {
  
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
  
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(String[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
  
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
}
Producción:

Initial Array:
Sun
Mon
Tue
Thu

Destination Array: 
Mon
Tue
Thu

Ejemplo 2: para ArgumentNullException

// C# program to demonstrate
// ConstrainedCopy() method
// For ArgumentNullException
using System;
using System.Collections.Generic;
   
class GFG {
   
// Main Method
public static void Main()
{
   
    try {
   
        // Creating and initializing the
        // String Array with null
        String[] srcArr = null;
   
        // Creating the object of empty String Array
        String[] destArr = new String[10];
   
        // getting a ConstrainedCopy in destArr
        // from srcArr using method ConstrainedCopy()
        Console.WriteLine("Trying to get the ConstrainedCopy "
                                     +"while srcArr is null");
        Console.WriteLine();
        Array.ConstrainedCopy(srcArr, 1, destArr, 0, 3);
   
        // Display the value of the destArr.
        Console.WriteLine("Destination Array: ");
   
        // calling the PrintIndexAndValues()
        // method to print
        PrintIndexAndValues(destArr);
    }
    catch (ArgumentNullException e) {
   
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (RankException e) {
   
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArrayTypeMismatchException e) {
   
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (InvalidCastException e) {
   
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentOutOfRangeException e) {
   
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentException e) {
   
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
}
   
    // Defining the method
    // PrintIndexAndValues
    public static void PrintIndexAndValues(String[] myArr)
    {
        for (int i = 0; i < myArr.Length; i++) {
   
            Console.WriteLine("{0}", myArr[i]);
        }
        Console.WriteLine();
    }
}
Producción:

Trying to get the ConstrainedCopy while srcArr is null

Exception Thrown: System.ArgumentNullException

Ejemplo 3: Para RankException

// C# program to demonstrate
// ConstrainedCopy() method
// For RankException
using System;
using System.Collections.Generic;
   
public class GFG {
   
// Main Method
public static void Main()
{
  
    try {
  
        // Creating and initializing new the String
        String[] srcArr = { "Sun", "Mon", "Tue", "Thu" };
  
        // Creating the object of empty String Array
        String[, ] destArr = new String[10, 5];
  
        // Display the values of the myArr.
        Console.WriteLine("Initial Array:");
  
        // calling the PrintIndexAndValues()
        // method to print
        PrintIndexAndValues(srcArr);
  
        // getting a ConstrainedCopy in destArr
        // from srcArr using method ConstrainedCopy()
        Console.WriteLine("Trying to get the ConstrainedCopy "
                                     +"in destArr of rank 2");
        Console.WriteLine("while rank of srcArr is 1");
        Array.ConstrainedCopy(srcArr, 1, destArr, 0, 3);
    }
    catch (ArgumentNullException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (RankException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArrayTypeMismatchException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (InvalidCastException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentOutOfRangeException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
}
  
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
    for (int i = 0; i < myArr.Length; i++) {
  
        Console.WriteLine("{0}", myArr[i]);
    }
    Console.WriteLine();
}
}
Producción:

Initial Array:
Sun
Mon
Tue
Thu

Trying to get the ConstrainedCopy in destArr of rank 2
while rank of srcArr is 1
Exception Thrown: System.RankException

Ejemplo 4: para ArrayTypeMismatchException

// C# program to demonstrate
// ConstrainedCopy() method
// For ArrayTypeMismatchException
using System;
using System.Collections.Generic;
   
class GFG {
   
// Main Method
public static void Main()
{
  
    try {
  
        // Creating and initializing new the String
        String[] srcArr = { "Sun", "Mon", "Tue", "Thu" };
  
        // Creating the object of
        // empty Integer Array
        int[] destArr = new int[10];
  
        // Display the values of the myArr.
        Console.WriteLine("Initial Array:");
  
        // calling the PrintIndexAndValues()
        // method to print
        PrintIndexAndValues(srcArr);
  
        // getting a ConstrainedCopy in destArr
        // from srcArr using method ConstrainedCopy()
        Console.WriteLine("Trying to get the "
          +"ConstrainedCopy in destArr of type int");
        Console.WriteLine("but srcArr is of type String");
        Array.ConstrainedCopy(srcArr, 1, destArr, 0, 3);
    }
    catch (ArgumentNullException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (RankException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArrayTypeMismatchException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (InvalidCastException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentOutOfRangeException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
}
  
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
    for (int i = 0; i < myArr.Length; i++) {
  
        Console.WriteLine("{0}", myArr[i]);
    }
    Console.WriteLine();
}
}
Producción:

Initial Array:
Sun
Mon
Tue
Thu

Trying to get the ConstrainedCopy in destArr of type int
but srcArr is of type String
Exception Thrown: System.ArrayTypeMismatchException

Ejemplo 5: para ArgumentOutOfRangeException

// C# program to demonstrate 
// ConstrainedCopy() method 
// For ArgumentOutOfRangeException
using System; 
using System.Collections.Generic; 
       
public class GFG { 
       
// Main Method 
public static void Main() 
{ 
   
  try { 
        
    // Creating and initializing 
    // new the String 
    String[] srcArr = {"Sun", "Mon", "Tue", "Thu"}; 
        
    // Creating the object of empty String Array 
    String[] destArr = new String[10]; 
   
    // Display the values of the myArr. 
    Console.WriteLine("Initial Array:"); 
   
    // calling the PrintIndexAndValues()  
    // method to print 
    PrintIndexAndValues(srcArr); 
   
    // getting a ConstrainedCopy
    // in destArr from srcArr 
    // using method ConstrainedCopy() 
    Console.WriteLine("Trying to get the ConstrainedCopy"
                          +" of length less than zero");
    Array.ConstrainedCopy (srcArr,1,destArr ,0,-1);
   
  }
  catch (ArgumentNullException e) { 
   
        Console.Write("Exception Thrown: "); 
        Console.Write("{0}", e.GetType(), e.Message); 
    } 
  catch (RankException e) { 
   
        Console.Write("Exception Thrown: "); 
        Console.Write("{0}", e.GetType(), e.Message); 
    } 
  catch (ArrayTypeMismatchException e) { 
   
        Console.Write("Exception Thrown: "); 
        Console.Write("{0}", e.GetType(), e.Message); 
    } 
  catch (InvalidCastException e) { 
   
        Console.Write("Exception Thrown: "); 
        Console.Write("{0}", e.GetType(), e.Message); 
    } 
  catch (ArgumentOutOfRangeException e) { 
   
        Console.Write("Exception Thrown: "); 
        Console.Write("{0}", e.GetType(), e.Message); 
    } 
  catch (ArgumentException e) { 
   
        Console.Write("Exception Thrown: "); 
        Console.Write("{0}", e.GetType(), e.Message); 
    } 
} 
   
// Defining the method  
// PrintIndexAndValues 
public static void PrintIndexAndValues(String[] myArr) 
{ 
    for (int i = 0; i < myArr.Length; i++) { 
   
        Console.WriteLine("{0}", myArr[i]); 
    } 
    Console.WriteLine(); 
} 
}
Producción:

Initial Array:
Sun
Mon
Tue
Thu

Trying to get the ConstrainedCopy of length less than zero
Exception Thrown: System.ArgumentOutOfRangeException

Ejemplo 6: Para ArgumentException

// C# program to demonstrate
// ConstrainedCopy() method
// For ArgumentException
using System;
using System.Collections.Generic;
  
public class GFG {
  
// Main Method
public static void Main()
{
  
    try {
  
        // Creating and initializing new the String
        String[] srcArr = { "Sun", "Mon", "Tue", "Thu" };
  
        // Creating the object of empty String Array
        String[] destArr = new String[10];
  
        // Display the values of the myArr.
        Console.WriteLine("Initial Array:");
  
        // calling the PrintIndexAndValues()
        // method to print
        PrintIndexAndValues(srcArr);
  
        // getting a ConstrainedCopy 
        // in destArr from srcArr
        // using method ConstrainedCopy()
        Console.WriteLine("Trying to get the ConstrainedCopy"
                  +" of length is greater than the number ");
        Console.WriteLine("of elements from sourceIndex"
                    +" to the end of sourceArray.");
        Console.WriteLine();
        Array.ConstrainedCopy(srcArr, 1, destArr, 0, 4);
    }
    catch (ArgumentNullException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (RankException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArrayTypeMismatchException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (InvalidCastException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentOutOfRangeException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
    catch (ArgumentException e) {
  
        Console.Write("Exception Thrown: ");
        Console.Write("{0}", e.GetType(), e.Message);
    }
}
  
// Defining the method
// PrintIndexAndValues
public static void PrintIndexAndValues(String[] myArr)
{
    for (int i = 0; i < myArr.Length; i++) {
  
        Console.WriteLine("{0}", myArr[i]);
    }
    Console.WriteLine();
}
}
Producción:

Initial Array:
Sun
Mon
Tue
Thu

Trying to get the ConstrainedCopy of length is greater than the number 
of elements from sourceIndex to the end of sourceArray.

Exception Thrown: System.ArgumentException

Referencia:

Publicación traducida automáticamente

Artículo escrito por RohitPrasad3 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *