Compartir vía


Array.AsReadOnly<T>(T[]) Método

Definición

Devuelve un contenedor de solo lectura para la matriz especificada.

public:
generic <typename T>
 static System::Collections::ObjectModel::ReadOnlyCollection<T> ^ AsReadOnly(cli::array <T> ^ array);
public static System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly<T> (T[] array);
static member AsReadOnly : 'T[] -> System.Collections.ObjectModel.ReadOnlyCollection<'T>
Public Shared Function AsReadOnly(Of T) (array As T()) As ReadOnlyCollection(Of T)

Parámetros de tipo

T

Tipo de los elementos de la matriz.

Parámetros

array
T[]

Matriz unidimensional de base cero para ajustar en un contenedor ReadOnlyCollection<T> de solo lectura.

Devoluciones

ReadOnlyCollection<T>

Contenedor ReadOnlyCollection<T> de solo lectura para la matriz especificada.

Excepciones

array es null.

Ejemplos

En el ejemplo siguiente se ajusta una matriz en un objeto de solo ReadOnlyCollection<T>lectura.

using namespace System;
using namespace System::Collections::Generic;

namespace Samples
{
    public ref class SamplesArray
    {
    public:
        static void Work()
        {

            // Create and initialize a new string array.
            array <String^>^ textArray = 
                {"The", "quick", "brown", "fox"};

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

            // Create a read-only IList wrapper around the array.
            IList <String^>^ textList = Array::AsReadOnly(textArray);

            // Display the values of the read-only IList.
            Console::WriteLine("The read-only IList contains " 
                "the following values:");
            PrintIndexAndValues(textList);

            // Attempt to change a value through the wrapper.
            try
            {
                textList[3] = "CAT";
            }
            catch (NotSupportedException^ ex) 
            {
                Console::WriteLine("{0} - {1}", ex->GetType(), 
                    ex->Message);
                Console::WriteLine();
            }


            // Change a value in the original array.
            textArray[2] = "RED";

            // Display the values of the array.
            Console::WriteLine("After changing the third element," 
                "the string array contains the following values:");
            PrintIndexAndValues(textArray);

            // Display the values of the read-only IList.
            Console::WriteLine("After changing the third element, the" 
                " read-only IList contains the following values:");
            PrintIndexAndValues(textList);
        }

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

        static void PrintIndexAndValues(IList<String^>^ textList)
        {
            for (int i = 0; i < textList->Count; i++)
            {
                Console::WriteLine("   [{0}] : {1}", i, textList[i]);
            }
            Console::WriteLine();
        }
    };
}

int main()
{
    Samples::SamplesArray::Work();

}

/* 
This code produces the following output.

The string array initially contains the following values:
[0] : The
[1] : quick
[2] : brown
[3] : fox

The read-only IList contains the following values:
[0] : The
[1] : quick
[2] : brown
[3] : fox

System.NotSupportedException - Collection is read-only.

After changing the third element, the string array contains the following values:
[0] : The
[1] : quick
[2] : RED
[3] : fox

After changing the third element, the read-only IList contains the following values:
[0] : The
[1] : quick
[2] : RED
[3] : fox

*/
using System;
using System.Collections.Generic;

public class SamplesArray  {

   public static void Main()  {

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

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

      // Create a read-only IList wrapper around the array.
      IList<string> myList = Array.AsReadOnly( myArr );

      // Display the values of the read-only IList.
      Console.WriteLine( "The read-only IList contains the following values:" );
      PrintIndexAndValues( myList );

      // Attempt to change a value through the wrapper.
      try  {
         myList[3] = "CAT";
      }
      catch ( NotSupportedException e )  {
         Console.WriteLine( "{0} - {1}", e.GetType(), e.Message );
         Console.WriteLine();
      }

      // Change a value in the original array.
      myArr[2] = "RED";

      // Display the values of the array.
      Console.WriteLine( "After changing the third element, the string array contains the following values:" );
      PrintIndexAndValues( myArr );

      // Display the values of the read-only IList.
      Console.WriteLine( "After changing the third element, the read-only IList contains the following values:" );
      PrintIndexAndValues( myList );
   }

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

   public static void PrintIndexAndValues( IList<string> myList )  {
      for ( int i = 0; i < myList.Count; i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, myList[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

The read-only IList contains the following values:
   [0] : The
   [1] : quick
   [2] : brown
   [3] : fox

System.NotSupportedException - Collection is read-only.

After changing the third element, the string array contains the following values:
   [0] : The
   [1] : quick
   [2] : RED
   [3] : fox

After changing the third element, the read-only IList contains the following values:
   [0] : The
   [1] : quick
   [2] : RED
   [3] : fox

*/
open System
open System.Collections.Generic

let printIndexAndValues (myList: IList<'a>) =
    for i = 0 to myList.Count - 1 do
        printfn $"   [{i}] : {myList[i]}"
    printfn ""

// Create and initialize a new string array.
let myArr = [| "The"; "quick"; "brown"; "fox" |]

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

// Create a read-only IList wrapper around the array.
let myList: IList<_> = Array.AsReadOnly myArr

// Display the values of the read-only IList.
printfn "The read-only IList contains the following values:"
printIndexAndValues myList

// Attempt to change a value through the wrapper.
try 
    myList[3] <- "CAT"

with :? NotSupportedException as e ->
    printfn $"{e.GetType()} - {e.Message}\n"

// Change a value in the original array.
myArr[2] <- "RED"

// Display the values of the array.
printfn "After changing the third element, the string array contains the following values:"
printIndexAndValues myArr

// Display the values of the read-only IList.
printfn "After changing the third element, the read-only IList contains the following values:"
printIndexAndValues myList


// This code produces the following output.
//     The string array initially contains the following values:
//        [0] : The
//        [1] : quick
//        [2] : brown
//        [3] : fox
//     
//     The read-only IList contains the following values:
//        [0] : The
//        [1] : quick
//        [2] : brown
//        [3] : fox
//     
//     System.NotSupportedException - Collection is read-only.
//     
//     After changing the third element, the string array contains the following values:
//        [0] : The
//        [1] : quick
//        [2] : RED
//        [3] : fox
//     
//     After changing the third element, the read-only IList contains the following values:
//        [0] : The
//        [1] : quick
//        [2] : RED
//        [3] : fox
Imports System.Collections.Generic

Public Class SamplesArray

    Public Shared Sub Main()

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

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

        ' Create a read-only IList wrapper around the array.
        Dim myList As IList(Of String) = Array.AsReadOnly(myArr) '

        ' Display the values of the read-only IList.
        Console.WriteLine("The read-only IList contains the following values:")
        PrintIndexAndValues(myList)

        ' Attempt to change a value through the wrapper.
        Try
            myList(3) = "CAT"
        Catch e As NotSupportedException
            Console.WriteLine("{0} - {1}", e.GetType(), e.Message)
            Console.WriteLine()
        End Try

        ' Change a value in the original array.
        myArr(2) = "RED"

        ' Display the values of the array.
        Console.WriteLine("After changing the third element, the string array contains the following values:")
        PrintIndexAndValues(myArr)

        ' Display the values of the read-only IList.
        Console.WriteLine("After changing the third element, the read-only IList contains the following values:")
        PrintIndexAndValues(myList)

    End Sub

    Overloads 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

    Overloads Public Shared Sub PrintIndexAndValues(myList As IList(Of String))
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine("   [{0}] : {1}", i, myList(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
'
'The read-only IList contains the following values:
'   [0] : The
'   [1] : quick
'   [2] : brown
'   [3] : fox
'
'System.NotSupportedException - Collection is read-only.
'
'After changing the third element, the string array contains the following values:
'   [0] : The
'   [1] : quick
'   [2] : RED
'   [3] : fox
'
'After changing the third element, the read-only IList contains the following values:
'   [0] : The
'   [1] : quick
'   [2] : RED
'   [3] : fox

Comentarios

Para evitar modificaciones en la matriz, exponga la matriz solo a través de este contenedor.

Una colección que es de solo lectura es simplemente una colección con un contenedor que impide modificar la colección; por lo tanto, si se realizan cambios en la colección subyacente, la colección de solo lectura refleja esos cambios.

Este método es una operación O(1).

Se aplica a