ReadOnlyCollectionBase Classe
Definição
Fornece a classe base abstract para uma coleção somente leitura fortemente tipada não genérica.Provides the abstract base class for a strongly typed non-generic read-only collection.
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
- Herança
-
ReadOnlyCollectionBase
- Derivado
- Atributos
- Implementações
Exemplos
O exemplo de código a seguir implementa a ReadOnlyCollectionBase classe.The following code example implements the ReadOnlyCollectionBase class.
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.
Comentários
Uma ReadOnlyCollectionBase instância é sempre somente leitura.A ReadOnlyCollectionBase instance is always read-only. Consulte CollectionBase para obter uma versão modificável desta classe.See CollectionBase for a modifiable version of this class.
Importante
Não recomendamos que você use a ReadOnlyCollectionBase classe para o novo desenvolvimento.We don't recommend that you use the ReadOnlyCollectionBase class for new development. Em vez disso, recomendamos que você use a ReadOnlyCollection<T> classe genérica.Instead, we recommend that you use the generic ReadOnlyCollection<T> class. Para obter mais informações, consulte coleções não genéricas não devem ser usadas no github.For more information, see Non-generic collections shouldn't be used on GitHub.
Notas aos Implementadores
Essa classe base é fornecida para tornar mais fácil para os implementadores criar uma coleção personalizada somente leitura com rigidez de tipos.This base class is provided to make it easier for implementers to create a strongly typed read-only custom collection. Os implementadores são incentivados a estender essa classe base em vez de criar suas próprias.Implementers are encouraged to extend this base class instead of creating their own. Os membros desta classe base são protegidos e devem ser usados somente por meio de uma classe derivada.Members of this base class are protected and are intended to be used through a derived class only.
Essa classe torna a coleção subjacente disponível por meio da InnerList propriedade, que é destinada ao uso somente por classes derivadas diretamente do ReadOnlyCollectionBase .This class makes the underlying collection available through the InnerList property, which is intended for use only by classes that are derived directly from ReadOnlyCollectionBase. A classe derivada deve garantir que seus próprios usuários não possam modificar a coleção subjacente.The derived class must ensure that its own users cannot modify the underlying collection.
Construtores
| ReadOnlyCollectionBase() |
Inicializa uma nova instância da classe ReadOnlyCollectionBase.Initializes a new instance of the ReadOnlyCollectionBase class. |
Propriedades
| Count |
Obtém o número de elementos contidos na instância de ReadOnlyCollectionBase.Gets the number of elements contained in the ReadOnlyCollectionBase instance. |
| InnerList |
Obtém a lista de elementos contidos na instância ReadOnlyCollectionBase.Gets the list of elements contained in the ReadOnlyCollectionBase instance. |
Métodos
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetEnumerator() |
Retorna um enumerador que itera pela instância ReadOnlyCollectionBase.Returns an enumerator that iterates through the ReadOnlyCollectionBase instance. |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |
Implantações explícitas de interface
| ICollection.CopyTo(Array, Int32) |
Copia todo o ReadOnlyCollectionBase em um Array unidimensional compatível, começando no índice especificado da matriz de destino.Copies the entire ReadOnlyCollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array. |
| ICollection.IsSynchronized |
Obtém um valor que indica se o acesso a um objeto ReadOnlyCollectionBase é sincronizado (thread-safe).Gets a value indicating whether access to a ReadOnlyCollectionBase object is synchronized (thread safe). |
| ICollection.SyncRoot |
Obtém um objeto que pode ser usado para sincronizar o acesso a um objeto ReadOnlyCollectionBase.Gets an object that can be used to synchronize access to a ReadOnlyCollectionBase object. |
Métodos de Extensão
| Cast<TResult>(IEnumerable) |
Converte os elementos de um IEnumerable para o tipo especificado.Casts the elements of an IEnumerable to the specified type. |
| OfType<TResult>(IEnumerable) |
Filtra os elementos de um IEnumerable com base em um tipo especificado.Filters the elements of an IEnumerable based on a specified type. |
| AsParallel(IEnumerable) |
Habilita a paralelização de uma consulta.Enables parallelization of a query. |
| AsQueryable(IEnumerable) |
Converte um IEnumerable em um IQueryable.Converts an IEnumerable to an IQueryable. |
Aplica-se a
Acesso thread-safe
Os membros estáticos públicos (Shared no Visual Basic) desse são thread-safe.Public static (Shared in Visual Basic) members of this type are thread safe. Não há garantia de que qualquer membro de instância seja seguro para threads.Any instance members are not guaranteed to be thread safe.
Essa implementação não fornece um wrapper sincronizado (thread-safe) para uma ReadOnlyCollectionBase , mas classes derivadas podem criar suas próprias versões sincronizadas do ReadOnlyCollectionBase usando a SyncRoot propriedade.This implementation does not provide a synchronized (thread safe) wrapper for a ReadOnlyCollectionBase, but derived classes can create their own synchronized versions of the ReadOnlyCollectionBase using the SyncRoot property.
A enumeração por meio de uma coleção não é um procedimento thread-safe intrínseco.Enumerating through a collection is intrinsically not a thread-safe procedure. Mesmo quando uma coleção está sincronizada, outros threads ainda podem modificar a coleção, o que faz o enumerador lançar uma exceção.Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. Para garantir thread-safe durante a enumeração, é possível bloquear a coleção durante toda a enumeração ou verificar as exceções resultantes das alterações feitas por outros threads.To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.