ReadOnlyCollectionBase Classe

Definizione

Fornisce la classe base abstract per una raccolta di sola lettura non generica fortemente tipizzata.

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
Ereditarietà
ReadOnlyCollectionBase
Derivato
Attributi
Implementazioni

Esempio

Nell'esempio di codice seguente viene implementata la ReadOnlyCollectionBase classe .

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.

Commenti

Un'istanza ReadOnlyCollectionBase è sempre di sola lettura. Vedere CollectionBase per una versione modificabile di questa classe.

Importante

Non è consigliabile usare la ReadOnlyCollectionBase classe per il nuovo sviluppo. È invece consigliabile usare la classe generica ReadOnlyCollection<T> . Per altre informazioni, vedere Raccolte non generiche non devono essere usate in GitHub.

Note per gli implementatori

Questa classe di base viene fornita per semplificare l'implementazione per creare una raccolta personalizzata fortemente tipizzata di sola lettura. Gli implementatori sono invitati a estendere questa classe di base anziché crearne uno. I membri di questa classe di base sono protetti e devono essere usati solo tramite una classe derivata.

Questa classe rende disponibile la raccolta sottostante tramite la proprietà, destinata all'uso InnerList solo da classi derivate direttamente da ReadOnlyCollectionBase. La classe derivata deve assicurarsi che i propri utenti non possano modificare la raccolta sottostante.

Costruttori

ReadOnlyCollectionBase()

Inizializza una nuova istanza della classe ReadOnlyCollectionBase.

Proprietà

Count

Ottiene il numero di elementi contenuti nell'istanza di ReadOnlyCollectionBase.

InnerList

Ottiene l'elenco degli elementi contenuti nell'istanza di ReadOnlyCollectionBase.

Metodi

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetEnumerator()

Restituisce un enumeratore per lo scorrimento dell'istanza di ReadOnlyCollectionBase.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

ICollection.CopyTo(Array, Int32)

Copia l'intero oggetto ReadOnlyCollectionBase in un oggetto Array compatibile unidimensionale, a partire dall'indice specificato della matrice di destinazione.

ICollection.IsSynchronized

Ottiene un valore che indica se l'accesso a un oggetto ReadOnlyCollectionBase è sincronizzato (thread-safe).

ICollection.SyncRoot

Ottiene un oggetto che può essere usato per sincronizzare l'accesso all'oggetto ReadOnlyCollectionBase.

Metodi di estensione

Cast<TResult>(IEnumerable)

Esegue il cast degli elementi di un oggetto IEnumerable nel tipo specificato.

OfType<TResult>(IEnumerable)

Filtra gli elementi di un oggetto IEnumerable in base a un tipo specificato.

AsParallel(IEnumerable)

Consente la parallelizzazione di una query.

AsQueryable(IEnumerable)

Converte un oggetto IEnumerable in un oggetto IQueryable.

Si applica a

Thread safety

I membri statici pubblici (Shared in Visual Basic) di questo tipo sono thread safe. Non è invece garantita la sicurezza dei membri dell'istanza.

Questa implementazione non fornisce un wrapper sincronizzato (thread safe) per un ReadOnlyCollectionBaseoggetto , ma le classi derivate possono creare le proprie versioni sincronizzate dell'uso ReadOnlyCollectionBase della SyncRoot proprietà .

L'enumerazione di una raccolta non è di per sé una procedura thread-safe. Anche se una raccolta è sincronizzata, è possibile che venga modificata da altri thread, con conseguente generazione di un'eccezione da parte dell'enumeratore. Per garantire la protezione dei thread durante l'enumerazione, è possibile bloccare la raccolta per l'intera enumerazione oppure intercettare le eccezioni determinate dalle modifiche apportate da altri thread.

Vedi anche