List<T>.AsReadOnly Метод

Определение

Возвращает оболочку только ReadOnlyCollection<T> для чтения для текущей коллекции.

public:
 System::Collections::ObjectModel::ReadOnlyCollection<T> ^ AsReadOnly();
public System.Collections.ObjectModel.ReadOnlyCollection<T> AsReadOnly();
member this.AsReadOnly : unit -> System.Collections.ObjectModel.ReadOnlyCollection<'T>
Public Function AsReadOnly () As ReadOnlyCollection(Of T)

Возвращаемое значение

Объект, который выступает в качестве оболочки только для чтения вокруг текущего List<T>объекта.

Примеры

В следующем примере демонстрируется AsReadOnly метод. List<T> Создается строка с емкостью 4, так как конечный размер списка, как известно, ровно 4. Список заполняется четырьмя строками, а AsReadOnly метод используется для получения реализации универсального интерфейса только для IList<T> чтения, которая упаковывает исходный список.

Элемент исходного списка имеет значение "Coelophysis" с помощью Item[] свойства (индексатора в C#), а содержимое списка только для чтения отображается, чтобы продемонстрировать, что это просто оболочка для исходного списка.

using System;
using System.Collections.Generic;

public partial class Program
{
    public static void Main()
    {
        List<string> animals = new List<string>(4);

        Console.WriteLine("\nCapacity: {0}", animals.Capacity);

        animals.Add("Cat");
        animals.Add("Dog");
        animals.Add("Squirrel");
        animals.Add("Wolf");

        Console.WriteLine();
        foreach (string animal in animals)
        {
            Console.WriteLine(animal);
        }

        Console.WriteLine("\nIList<string> roAnimals = animals.AsReadOnly()");
        IList<string> roAnimals = animals.AsReadOnly();

        Console.WriteLine("\nElements in the read-only IList:");
        foreach (string animal in roAnimals)
        {
            Console.WriteLine(animal);
        }

        Console.WriteLine("\nanimals[2] = \"Lion\"");
        animals[2] = "Lion";

        Console.WriteLine("\nElements in the read-only IList:");
        foreach (string animal in roAnimals)
        {
            Console.WriteLine(animal);
        }
    }
}

/*
    This code example produces the following output:

    Capacity: 4

    Cat
    Dog
    Squirrel
    Wolf

    IList<string> roAnimals = animals.AsReadOnly()

    Elements in the read-only IList:
    Cat
    Dog
    Squirrel
    Wolf

    animals[2] = "Lion"

    Elements in the read-only IList:
    Cat
    Dog
    Lion
    Wolf
*/
Imports System.Collections.Generic

Partial Public Class Program
    Public Shared Sub Main()

        Dim animals As New List(Of String)(4)

        Console.WriteLine(vbLf & "Capacity: {0}", animals.Capacity)

        animals.Add("Cat")
        animals.Add("Dog")
        animals.Add("Squirrel")
        animals.Add("Wolf")

        Console.WriteLine()
        For Each animal As String In animals
            Console.WriteLine(animal)
        Next

        Console.WriteLine(vbLf & _
            "Dim roAnimals As IList(Of String) = animals.AsReadOnly")
        Dim roAnimals As IList(Of String) = animals.AsReadOnly

        Console.WriteLine(vbLf & "Elements in the read-only IList:")
        For Each animal As String In roAnimals
            Console.WriteLine(animal)
        Next

        Console.WriteLine(vbLf & "animals(2) = ""Lion""")
        animals(2) = "Lion"

        Console.WriteLine(vbLf & "Elements in the read-only IList:")
        For Each animal As String In roAnimals
            Console.WriteLine(animal)
        Next

    End Sub
End Class

' This code example produces the following output:
'
' Capacity: 4
'
' Cat
' Dog
' Squirrel
' Wolf
'
' Dim roAnimals As IList(Of String) = animals.AsReadOnly
'
' Elements in the read-only IList:
' Cat
' Dog
' Squirrel
' Wolf
'
' animals(2) = "Lion"
'
' Elements in the read-only IList:
' Cat
' Dog
' Lion
' Wolf

Комментарии

Чтобы предотвратить любые изменения List<T> объекта, предостерейте его только через эту оболочку. Объект ReadOnlyCollection<T> не предоставляет методы, изменяющие коллекцию. Однако если изменения вносятся в базовый List<T> объект, коллекция только для чтения отражает эти изменения.

Этот метод является операцией O(1).

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