C# | Creación de un contenedor de solo lectura para List

El método List<T>.AsReadOnly se usa para obtener un contenedor ReadOnlyCollection<T> de solo lectura para la colección actual.

Sintaxis:

public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly();

Valor de retorno: devuelve un objeto que actúa como un contenedor de solo lectura alrededor de la List<T> actual .

Ejemplo:

// C# code to create a read-only
// wrapper for the List<T>
using System;
using System.Collections.Generic;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an List<T> of Integers
        List<int> mylist = new List<int>();
  
        // Adding elements to List
        mylist.Add(17);
        mylist.Add(19);
        mylist.Add(21);
        mylist.Add(9);
        mylist.Add(75);
        mylist.Add(19);
        mylist.Add(73);
  
        Console.WriteLine("Before Wrapping: ");
  
        // Displaying the elements
        // in the mylist
        foreach(int i in mylist)
        {
            Console.WriteLine(i);
        }
  
        // Creating a Read-Only packing
        // around the List
        IList<int> readlist = mylist.AsReadOnly();
  
        Console.WriteLine("After Wrapping: ");
  
        // Displaying the elements
        // of Read-Only Collection
        foreach(int j in readlist)
        {
            Console.WriteLine(j);
        }
          
        // You can add elements to
        // the original List i.e. mylist
        Console.WriteLine("Adding new element to mylist: ");
        mylist.Add(35);
          
        // Displaying the elements
        // in the mylist
        foreach(int k in mylist)
        {
            Console.WriteLine(k);
        }
  
        // But you cannot add elements
        // into the Read-Only Collection
        Console.WriteLine("Trying to add new element into readlist:");
  
        // it will give error
        readlist.Add(34);
          
    }
}

Producción:

Before Wrapping: 
17
19
21
9
75
19
73
After Wrapping: 
17
19
21
9
75
19
73
Adding new element to mylist: 
17
19
21
9
75
19
73
35
Trying to add new element into readlist:

Error de tiempo de ejecución:

Excepción no controlada:
System.NotSupportedException: la colección es de solo lectura.

Referencia:

Publicación traducida automáticamente

Artículo escrito por Kirti_Mangal 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 *