ReadOnlyCollectionBase Klasa

Definicja

Udostępnia klasę abstract bazową dla silnie typizowanej kolekcji tylko do odczytu.

public ref class ReadOnlyCollectionBase abstract : System::Collections::ICollection
public abstract class ReadOnlyCollectionBase : System.Collections.ICollection
[System.Serializable]
public abstract class ReadOnlyCollectionBase : System.Collections.ICollection
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class ReadOnlyCollectionBase : System.Collections.ICollection
type ReadOnlyCollectionBase = class
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
type ReadOnlyCollectionBase = class
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type ReadOnlyCollectionBase = class
    interface ICollection
    interface IEnumerable
Public MustInherit Class ReadOnlyCollectionBase
Implements ICollection
Dziedziczenie
ReadOnlyCollectionBase
Pochodne
Atrybuty
Implementuje

Przykłady

Poniższy przykład kodu implementuje klasę ReadOnlyCollectionBase .

using namespace System;
using namespace System::Collections;
public ref class ROCollection: public ReadOnlyCollectionBase
{
public:
   ROCollection( IList^ sourceList )
   {
      InnerList->AddRange( sourceList );
   }

   property Object^ Item [int]
   {
      Object^ get( int index )
      {
         return (InnerList[ index ]);
      }

   }
   int IndexOf( Object^ value )
   {
      return (InnerList->IndexOf( value ));
   }

   bool Contains( Object^ value )
   {
      return (InnerList->Contains( value ));
   }

};

void PrintIndexAndValues( ROCollection^ myCol );
void PrintValues2( ROCollection^ myCol );
int main()
{
   // Create an ArrayList.
   ArrayList^ myAL = gcnew ArrayList;
   myAL->Add( "red" );
   myAL->Add( "blue" );
   myAL->Add( "yellow" );
   myAL->Add( "green" );
   myAL->Add( "orange" );
   myAL->Add( "purple" );

   // Create a new ROCollection that contains the elements in myAL.
   ROCollection^ myCol = gcnew ROCollection( myAL );

   // Display the contents of the collection using the enumerator.
   Console::WriteLine( "Contents of the collection (using enumerator):" );
   PrintValues2( myCol );

   // Display the contents of the collection using the Count property and the Item property.
   Console::WriteLine( "Contents of the collection (using Count and Item):" );
   PrintIndexAndValues( myCol );

   // Search the collection with Contains and IndexOf.
   Console::WriteLine( "Contains yellow: {0}", myCol->Contains( "yellow" ) );
   Console::WriteLine( "orange is at index {0}.", myCol->IndexOf( "orange" ) );
   Console::WriteLine();
}


// Uses the Count property and the Item property.
void PrintIndexAndValues( ROCollection^ myCol )
{
   for ( int i = 0; i < myCol->Count; i++ )
      Console::WriteLine( "   [{0}]:   {1}", i, myCol->Item[ i ] );
   Console::WriteLine();
}


// Uses the enumerator. 
void PrintValues2( ROCollection^ myCol )
{
   System::Collections::IEnumerator^ myEnumerator = myCol->GetEnumerator();
   while ( myEnumerator->MoveNext() )
      Console::WriteLine( "   {0}", myEnumerator->Current );

   Console::WriteLine();
}

/* 
This code produces the following output.

Contents of the collection (using enumerator):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using Count and Item):
   [0]:   red
   [1]:   blue
   [2]:   yellow
   [3]:   green
   [4]:   orange
   [5]:   purple

Contains yellow: True
orange is at index 4.

*/
using System;
using System.Collections;

public class ROCollection : ReadOnlyCollectionBase  {

   public ROCollection( IList sourceList )  {
      InnerList.AddRange( sourceList );
   }

   public Object this[ int index ]  {
      get  {
         return( InnerList[index] );
      }
   }

   public int IndexOf( Object value )  {
      return( InnerList.IndexOf( value ) );
   }

   public bool Contains( Object value )  {
      return( InnerList.Contains( value ) );
   }
}

public class SamplesCollectionBase  {

   public static void Main()  {

      // Create an ArrayList.
      ArrayList myAL = new ArrayList();
      myAL.Add( "red" );
      myAL.Add( "blue" );
      myAL.Add( "yellow" );
      myAL.Add( "green" );
      myAL.Add( "orange" );
      myAL.Add( "purple" );

      // Create a new ROCollection that contains the elements in myAL.
      ROCollection myCol = new ROCollection( myAL );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Contents of the collection (using foreach):" );
      PrintValues1( myCol );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Contents of the collection (using enumerator):" );
      PrintValues2( myCol );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Contents of the collection (using Count and Item):" );
      PrintIndexAndValues( myCol );

      // Search the collection with Contains and IndexOf.
      Console.WriteLine( "Contains yellow: {0}", myCol.Contains( "yellow" ) );
      Console.WriteLine( "orange is at index {0}.", myCol.IndexOf( "orange" ) );
      Console.WriteLine();
   }

   // Uses the Count property and the Item property.
   public static void PrintIndexAndValues( ROCollection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   [{0}]:   {1}", i, myCol[i] );
      Console.WriteLine();
   }

   // Uses the foreach statement which hides the complexity of the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues1( ROCollection myCol )  {
      foreach ( Object obj in myCol )
         Console.WriteLine( "   {0}", obj );
      Console.WriteLine();
   }

   // Uses the enumerator.
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues2( ROCollection myCol )  {
      System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.WriteLine( "   {0}", myEnumerator.Current );
      Console.WriteLine();
   }
}


/*
This code produces the following output.

Contents of the collection (using foreach):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using enumerator):
   red
   blue
   yellow
   green
   orange
   purple

Contents of the collection (using Count and Item):
   [0]:   red
   [1]:   blue
   [2]:   yellow
   [3]:   green
   [4]:   orange
   [5]:   purple

Contains yellow: True
orange is at index 4.

*/
Imports System.Collections

Public Class ROCollection
    Inherits ReadOnlyCollectionBase


    Public Sub New(sourceList As IList)
        InnerList.AddRange(sourceList)
    End Sub


    Default Public ReadOnly Property Item(index As Integer) As [Object]
        Get
            Return InnerList(index)
        End Get
    End Property


    Public Function IndexOf(value As [Object]) As Integer
        Return InnerList.IndexOf(value)
    End Function 'IndexOf


    Public Function Contains(value As [Object]) As Boolean
        Return InnerList.Contains(value)
    End Function 'Contains

End Class


Public Class SamplesCollectionBase

    Public Shared Sub Main()

        ' Create an ArrayList.
        Dim myAL As New ArrayList()
        myAL.Add("red")
        myAL.Add("blue")
        myAL.Add("yellow")
        myAL.Add("green")
        myAL.Add("orange")
        myAL.Add("purple")

        ' Create a new ROCollection that contains the elements in myAL.
        Dim myCol As New ROCollection(myAL)

        ' Display the contents of the collection using For Each. This is the preferred method.
        Console.WriteLine("Contents of the collection (using For Each):")
        PrintValues1(myCol)

        ' Display the contents of the collection using the enumerator.
        Console.WriteLine("Contents of the collection (using enumerator):")
        PrintValues2(myCol)

        ' Display the contents of the collection using the Count property and the Item property.
        Console.WriteLine("Contents of the collection (using Count and Item):")
        PrintIndexAndValues(myCol)

        ' Search the collection with Contains and IndexOf.
        Console.WriteLine("Contains yellow: {0}", myCol.Contains("yellow"))
        Console.WriteLine("orange is at index {0}.", myCol.IndexOf("orange"))
        Console.WriteLine()

    End Sub


    ' Uses the Count property and the Item property.
    Public Shared Sub PrintIndexAndValues(myCol As ROCollection)
        Dim i As Integer
        For i = 0 To myCol.Count - 1
            Console.WriteLine("   [{0}]:   {1}", i, myCol(i))
        Next i
        Console.WriteLine()
    End Sub


    ' Uses the For Each statement which hides the complexity of the enumerator.
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues1(myCol As ROCollection)
        Dim obj As [Object]
        For Each obj In  myCol
            Console.WriteLine("   {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub


    ' Uses the enumerator. 
    ' NOTE: The For Each statement is the preferred way of enumerating the contents of a collection.
    Public Shared Sub PrintValues2(myCol As ROCollection)
        Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
        While myEnumerator.MoveNext()
            Console.WriteLine("   {0}", myEnumerator.Current)
        End While
        Console.WriteLine()
    End Sub

End Class


'This code produces the following output.
'
'Contents of the collection (using For Each):
'   red
'   blue
'   yellow
'   green
'   orange
'   purple
'
'Contents of the collection (using enumerator):
'   red
'   blue
'   yellow
'   green
'   orange
'   purple
'
'Contents of the collection (using Count and Item):
'   [0]:   red
'   [1]:   blue
'   [2]:   yellow
'   [3]:   green
'   [4]:   orange
'   [5]:   purple
'
'Contains yellow: True
'orange is at index 4.

Uwagi

ReadOnlyCollectionBase Wystąpienie jest zawsze tylko do odczytu. Zobacz CollectionBase , aby uzyskać modyfikowalną wersję tej klasy.

Ważne

Nie zalecamy używania ReadOnlyCollectionBase klasy do tworzenia nowych aplikacji. Zamiast tego zalecamy użycie klasy ogólnej ReadOnlyCollection<T> . Aby uzyskać więcej informacji, zobacz Kolekcje nieogólne nie powinny być używane w GitHub.

Uwagi dotyczące implementowania

Ta klasa bazowa jest udostępniana, aby ułatwić implementatorom tworzenie silnie typizowanej kolekcji niestandardowej tylko do odczytu. Implementacje są zachęcane do rozszerzania tej klasy bazowej zamiast tworzenia własnych. Składowe tej klasy bazowej są chronione i mają być używane tylko za pośrednictwem klasy pochodnej.

Ta klasa udostępnia podstawową kolekcję za pośrednictwem InnerList właściwości , która jest przeznaczona tylko dla klas, które pochodzą bezpośrednio z ReadOnlyCollectionBaseklasy . Klasa pochodna musi zapewnić, że jej użytkownicy nie mogą modyfikować podstawowej kolekcji.

Konstruktory

ReadOnlyCollectionBase()

Inicjuje nowe wystąpienie klasy ReadOnlyCollectionBase.

Właściwości

Count

Pobiera liczbę elementów zawartych w wystąpieniu ReadOnlyCollectionBase .

InnerList

Pobiera listę elementów zawartych w wystąpieniu ReadOnlyCollectionBase .

Metody

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetEnumerator()

Zwraca moduł wyliczający, który iteruje po wystąpieniu ReadOnlyCollectionBase .

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

ICollection.CopyTo(Array, Int32)

Kopiuje całość ReadOnlyCollectionBase do zgodnego jednowymiarowego Arrayobiektu , zaczynając od określonego indeksu tablicy docelowej.

ICollection.IsSynchronized

Pobiera wartość wskazującą ReadOnlyCollectionBase , czy dostęp do obiektu jest synchronizowany (bezpieczny wątek).

ICollection.SyncRoot

Pobiera obiekt, który może służyć do synchronizowania dostępu do ReadOnlyCollectionBase obiektu.

Metody rozszerzania

Cast<TResult>(IEnumerable)

Rzutuje elementy elementu IEnumerable na określony typ.

OfType<TResult>(IEnumerable)

Filtruje elementy IEnumerable elementu na podstawie określonego typu.

AsParallel(IEnumerable)

Umożliwia równoległość zapytania.

AsQueryable(IEnumerable)

Konwertuje element IEnumerable na .IQueryable

Dotyczy

Bezpieczeństwo wątkowe

Publiczne statyczne (Sharedw Visual Basic) składowe tego typu są bezpieczne wątkami. Wystąpienia elementów członkowskich nie dają gwarancji bezpieczeństwa wątków.

Ta implementacja nie zapewnia zsynchronizowanej (bezpiecznej wątku) otoki dla ReadOnlyCollectionBaseklasy pochodnej , ale klasy pochodne mogą tworzyć własne zsynchronizowane wersje ReadOnlyCollectionBase właściwości SyncRoot .

Wyliczanie w kolekcji nie jest wewnętrznie procedurą odporną na wielowątkowość. Nawet gdy kolekcja jest synchronizowana, inne wątki nadal mogą ją modyfikować. Powoduje to zgłaszanie wyjątku przez moduł wyliczający. Aby zagwarantować bezpieczeństwo wątków podczas wyliczania, można zablokować kolekcję podczas całego procesu wyliczania albo rejestrować wyjątki wynikłe ze zmian wprowadzanych przez inne wątków.

Zobacz też