CollectionBase CollectionBase CollectionBase CollectionBase Class

Definição

Fornece a classe base abstract para uma coleção fortemente tipada.Provides the abstract base class for a strongly typed collection.

public ref class CollectionBase abstract : System::Collections::IList
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public abstract class CollectionBase : System.Collections.IList
type CollectionBase = class
    interface IList
    interface ICollection
    interface IEnumerable
Public MustInherit Class CollectionBase
Implements IList
Herança
CollectionBaseCollectionBaseCollectionBaseCollectionBase
Derivado
Atributos
Implementações

Exemplos

O exemplo de código a seguir CollectionBase implementa a classe e usa essa implementação para criar uma Int16 coleção de objetos.The following code example implements the CollectionBase class and uses that implementation to create a collection of Int16 objects.

#using <System.dll>

using namespace System;
using namespace System::Collections;

public ref class Int16Collection: public CollectionBase
{
public:

   property Int16 Item [int]
   {
      Int16 get( int index )
      {
         return ( (Int16)(List[ index ]));
      }

      void set( int index, Int16 value )
      {
         List[ index ] = value;
      }
   }
   int Add( Int16 value )
   {
      return (List->Add( value ));
   }

   int IndexOf( Int16 value )
   {
      return (List->IndexOf( value ));
   }

   void Insert( int index, Int16 value )
   {
      List->Insert( index, value );
   }

   void Remove( Int16 value )
   {
      List->Remove( value );
   }

   bool Contains( Int16 value )
   {
      // If value is not of type Int16, this will return false.
      return (List->Contains( value ));
   }

protected:
   virtual void OnInsert( int /*index*/, Object^ /*value*/ ) override
   {
      // Insert additional code to be run only when inserting values.
   }

   virtual void OnRemove( int /*index*/, Object^ /*value*/ ) override
   {
      // Insert additional code to be run only when removing values.
   }

   virtual void OnSet( int /*index*/, Object^ /*oldValue*/, Object^ /*newValue*/ ) override
   {
      // Insert additional code to be run only when setting values.
   }

   virtual void OnValidate( Object^ value ) override
   {
      if ( value->GetType() != Type::GetType( "System.Int16" ) )
            throw gcnew ArgumentException( "value must be of type Int16.","value" );
   }

};

void PrintIndexAndValues( Int16Collection^ myCol );
void PrintValues2( Int16Collection^ myCol );
int main()
{
   // Create and initialize a new CollectionBase.
   Int16Collection^ myI16 = gcnew Int16Collection;
   
   // Add elements to the collection.
   myI16->Add( (Int16)1 );
   myI16->Add( (Int16)2 );
   myI16->Add( (Int16)3 );
   myI16->Add( (Int16)5 );
   myI16->Add( (Int16)7 );

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

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

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

   // Insert an element into the collection at index 3.
   myI16->Insert( 3, (Int16)13 );
   Console::WriteLine( "Contents of the collection after inserting at index 3:" );
   PrintIndexAndValues( myI16 );

   // Get and set an element using the index.
   myI16->Item[ 4 ] = 123;
   Console::WriteLine( "Contents of the collection after setting the element at index 4 to 123:" );
   PrintIndexAndValues( myI16 );

   // Remove an element from the collection.
   myI16->Remove( (Int16)2 );

   // Display the contents of the collection using the Count property and the Item property.
   Console::WriteLine( "Contents of the collection after removing the element 2:" );
   PrintIndexAndValues( myI16 );
}

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

// Uses the enumerator. 
void PrintValues2( Int16Collection^ 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):
   1
   2
   3
   5
   7

Initial contents of the collection (using Count and Item):
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   5
   [4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   5
   [5]:   7

Contents of the collection after setting the element at index 4 to 123:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   123
   [5]:   7

Contents of the collection after removing the element 2:
   [0]:   1
   [1]:   3
   [2]:   13
   [3]:   123
   [4]:   7

*/
using System;
using System.Collections;

public class Int16Collection : CollectionBase  {

   public Int16 this[ int index ]  {
      get  {
         return( (Int16) List[index] );
      }
      set  {
         List[index] = value;
      }
   }

   public int Add( Int16 value )  {
      return( List.Add( value ) );
   }

   public int IndexOf( Int16 value )  {
      return( List.IndexOf( value ) );
   }

   public void Insert( int index, Int16 value )  {
      List.Insert( index, value );
   }

   public void Remove( Int16 value )  {
      List.Remove( value );
   }

   public bool Contains( Int16 value )  {
      // If value is not of type Int16, this will return false.
      return( List.Contains( value ) );
   }

   protected override void OnInsert( int index, Object value )  {
      // Insert additional code to be run only when inserting values.
   }

   protected override void OnRemove( int index, Object value )  {
      // Insert additional code to be run only when removing values.
   }

   protected override void OnSet( int index, Object oldValue, Object newValue )  {
      // Insert additional code to be run only when setting values.
   }

   protected override void OnValidate( Object value )  {
      if ( value.GetType() != typeof(System.Int16) )
         throw new ArgumentException( "value must be of type Int16.", "value" );
   }

}


public class SamplesCollectionBase  {

   public static void Main()  {
 
      // Create and initialize a new CollectionBase.
      Int16Collection myI16 = new Int16Collection();

      // Add elements to the collection.
      myI16.Add( (Int16) 1 );
      myI16.Add( (Int16) 2 );
      myI16.Add( (Int16) 3 );
      myI16.Add( (Int16) 5 );
      myI16.Add( (Int16) 7 );

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

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

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

      // Search the collection with Contains and IndexOf.
      Console.WriteLine( "Contains 3: {0}", myI16.Contains( 3 ) );
      Console.WriteLine( "2 is at index {0}.", myI16.IndexOf( 2 ) );
      Console.WriteLine();

      // Insert an element into the collection at index 3.
      myI16.Insert( 3, (Int16) 13 );
      Console.WriteLine( "Contents of the collection after inserting at index 3:" );
      PrintIndexAndValues( myI16 );

      // Get and set an element using the index.
      myI16[4] = 123;
      Console.WriteLine( "Contents of the collection after setting the element at index 4 to 123:" );
      PrintIndexAndValues( myI16 );

      // Remove an element from the collection.
      myI16.Remove( (Int16) 2 );

      // Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine( "Contents of the collection after removing the element 2:" );
      PrintIndexAndValues( myI16 );

   }
 
   // Uses the Count property and the Item property.
   public static void PrintIndexAndValues( Int16Collection 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( Int16Collection myCol )  {
      foreach ( Int16 i16 in myCol )
         Console.WriteLine( "   {0}", i16 );
      Console.WriteLine();
   }

   // Uses the enumerator. 
   // NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
   public static void PrintValues2( Int16Collection 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):
   1
   2
   3
   5
   7

Contents of the collection (using enumerator):
   1
   2
   3
   5
   7

Initial contents of the collection (using Count and Item):
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   5
   [4]:   7

Contains 3: True
2 is at index 1.

Contents of the collection after inserting at index 3:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   5
   [5]:   7

Contents of the collection after setting the element at index 4 to 123:
   [0]:   1
   [1]:   2
   [2]:   3
   [3]:   13
   [4]:   123
   [5]:   7

Contents of the collection after removing the element 2:
   [0]:   1
   [1]:   3
   [2]:   13
   [3]:   123
   [4]:   7

*/

Imports System.Collections


Public Class Int16Collection
   Inherits CollectionBase


   Default Public Property Item(index As Integer) As Int16
      Get
         Return CType(List(index), Int16)
      End Get
      Set
         List(index) = value
      End Set
   End Property


   Public Function Add(value As Int16) As Integer
      Return List.Add(value)
   End Function 'Add

   Public Function IndexOf(value As Int16) As Integer
      Return List.IndexOf(value)
   End Function 'IndexOf


   Public Sub Insert(index As Integer, value As Int16)
      List.Insert(index, value)
   End Sub


   Public Sub Remove(value As Int16)
      List.Remove(value)
   End Sub


   Public Function Contains(value As Int16) As Boolean
      ' If value is not of type Int16, this will return false.
      Return List.Contains(value)
   End Function 'Contains


   Protected Overrides Sub OnInsert(index As Integer, value As Object)
      ' Insert additional code to be run only when inserting values.
   End Sub


   Protected Overrides Sub OnRemove(index As Integer, value As Object)
      ' Insert additional code to be run only when removing values.
   End Sub


   Protected Overrides Sub OnSet(index As Integer, oldValue As Object, newValue As Object)
      ' Insert additional code to be run only when setting values.
   End Sub


   Protected Overrides Sub OnValidate(value As Object)
      If Not GetType(System.Int16).IsAssignableFrom(value.GetType()) Then
         Throw New ArgumentException("value must be of type Int16.", "value")
      End If
   End Sub

End Class 'Int16Collection


Public Class SamplesCollectionBase

   Public Shared Sub Main()

      ' Creates and initializes a new CollectionBase.
      Dim myI16 As New Int16Collection()

      ' Adds elements to the collection.
      myI16.Add( 1 )
      myI16.Add( 2 )
      myI16.Add( 3 )
      myI16.Add( 5 )
      myI16.Add( 7 )

      ' Display the contents of the collection using For Each. This is the preferred method.
      Console.WriteLine("Contents of the collection (using For Each):")
      PrintValues1(myI16)
      
      ' Display the contents of the collection using the enumerator.
      Console.WriteLine("Contents of the collection (using enumerator):")
      PrintValues2(myI16)
      
      ' Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine("Initial contents of the collection (using Count and Item):")
      PrintIndexAndValues(myI16)
      
      ' Searches the collection with Contains and IndexOf.
      Console.WriteLine("Contains 3: {0}", myI16.Contains(3))
      Console.WriteLine("2 is at index {0}.", myI16.IndexOf(2))
      Console.WriteLine()
      
      ' Inserts an element into the collection at index 3.
      myI16.Insert(3, 13)
      Console.WriteLine("Contents of the collection after inserting at index 3:")
      PrintIndexAndValues(myI16)
      
      ' Gets and sets an element using the index.
      myI16(4) = 123
      Console.WriteLine("Contents of the collection after setting the element at index 4 to 123:")
      PrintIndexAndValues(myI16)
      
      ' Removes an element from the collection.
      myI16.Remove(2)

      ' Display the contents of the collection using the Count property and the Item property.
      Console.WriteLine("Contents of the collection after removing the element 2:")
      PrintIndexAndValues(myI16)

    End Sub


    ' Uses the Count property and the Item property.
    Public Shared Sub PrintIndexAndValues(myCol As Int16Collection)
      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 Int16Collection)
      Dim i16 As Int16
      For Each i16 In  myCol
          Console.WriteLine("   {0}", i16)
      Next i16
      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 Int16Collection)
      Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
      While myEnumerator.MoveNext()
          Console.WriteLine("   {0}", myEnumerator.Current)
      End While
      Console.WriteLine()
    End Sub

End Class 'SamplesCollectionBase


'This code produces the following output.
'
'Contents of the collection (using For Each):
'   1
'   2
'   3
'   5
'   7
'
'Contents of the collection (using enumerator):
'   1
'   2
'   3
'   5
'   7
'
'Initial contents of the collection (using Count and Item):
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   5
'   [4]:   7
'
'Contains 3: True
'2 is at index 1.
'
'Contents of the collection after inserting at index 3:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   13
'   [4]:   5
'   [5]:   7
'
'Contents of the collection after setting the element at index 4 to 123:
'   [0]:   1
'   [1]:   2
'   [2]:   3
'   [3]:   13
'   [4]:   123
'   [5]:   7
'
'Contents of the collection after removing the element 2:
'   [0]:   1
'   [1]:   3
'   [2]:   13
'   [3]:   123
'   [4]:   7

Comentários

Importante

Não recomendamos que você use a CollectionBase classe para o novo desenvolvimento.We don't recommend that you use the CollectionBase class for new development. Em vez disso, recomendamos que você use Collection<T> a classe genérica.Instead, we recommend that you use the generic Collection<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.

Uma CollectionBase instância é sempre modificável.A CollectionBase instance is always modifiable. Consulte ReadOnlyCollectionBase para obter uma versão somente leitura desta classe.See ReadOnlyCollectionBase for a read-only version of this class.

A capacidade de um CollectionBase é o número de elementos que CollectionBase o pode conter.The capacity of a CollectionBase is the number of elements the CollectionBase can hold. À medida que os elementos são CollectionBaseadicionados a um, a capacidade é aumentada automaticamente conforme necessário por meio de realocação.As elements are added to a CollectionBase, the capacity is automatically increased as required through reallocation. A capacidade pode ser diminuída definindo a Capacity Propriedade explicitamente.The capacity can be decreased by setting the Capacity property explicitly.

Notas aos Herdeiros

Essa classe base é fornecida para tornar mais fácil para os implementadores criar uma coleção personalizada fortemente tipada.This base class is provided to make it easier for implementers to create a strongly typed 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.

Construtores

CollectionBase() CollectionBase() CollectionBase() CollectionBase()

Inicializa uma nova instância da classe CollectionBase com a capacidade inicial padrão.Initializes a new instance of the CollectionBase class with the default initial capacity.

CollectionBase(Int32) CollectionBase(Int32) CollectionBase(Int32) CollectionBase(Int32)

Inicializa uma nova instância da classe CollectionBase com a capacidade especificada.Initializes a new instance of the CollectionBase class with the specified capacity.

Propriedades

Capacity Capacity Capacity Capacity

Obtém ou define o número de elementos que o CollectionBase pode conter.Gets or sets the number of elements that the CollectionBase can contain.

Count Count Count Count

Obtém o número de elementos contidos na instância CollectionBase.Gets the number of elements contained in the CollectionBase instance. Essa propriedade não pode ser substituída.This property cannot be overridden.

InnerList InnerList InnerList InnerList

Obtém uma ArrayList que contém a lista de elementos na instância de CollectionBase.Gets an ArrayList containing the list of elements in the CollectionBase instance.

List List List List

Obtém uma IList que contém a lista de elementos na instância de CollectionBase.Gets an IList containing the list of elements in the CollectionBase instance.

Métodos

Clear() Clear() Clear() Clear()

Remove todos os objetos da instância CollectionBase.Removes all objects from the CollectionBase instance. Esse método não pode ser substituído.This method cannot be overridden.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Retorna um enumerador que itera pela instância CollectionBase.Returns an enumerator that iterates through the CollectionBase instance.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
OnClear() OnClear() OnClear() OnClear()

Executa processos personalizados adicionais ao limpar o conteúdo da instância CollectionBase.Performs additional custom processes when clearing the contents of the CollectionBase instance.

OnClearComplete() OnClearComplete() OnClearComplete() OnClearComplete()

Executa processos adicionais personalizados após limpar o conteúdo da instância CollectionBase.Performs additional custom processes after clearing the contents of the CollectionBase instance.

OnInsert(Int32, Object) OnInsert(Int32, Object) OnInsert(Int32, Object) OnInsert(Int32, Object)

Executa os processos personalizados adicionais antes de inserir um novo elemento na instância CollectionBase.Performs additional custom processes before inserting a new element into the CollectionBase instance.

OnInsertComplete(Int32, Object) OnInsertComplete(Int32, Object) OnInsertComplete(Int32, Object) OnInsertComplete(Int32, Object)

Executa processos personalizados adicionais após inserir um novo elemento na instância de CollectionBase.Performs additional custom processes after inserting a new element into the CollectionBase instance.

OnRemove(Int32, Object) OnRemove(Int32, Object) OnRemove(Int32, Object) OnRemove(Int32, Object)

Executa processos personalizados adicionais ao remover um elemento da instância CollectionBase.Performs additional custom processes when removing an element from the CollectionBase instance.

OnRemoveComplete(Int32, Object) OnRemoveComplete(Int32, Object) OnRemoveComplete(Int32, Object) OnRemoveComplete(Int32, Object)

Executa processos personalizados adicionais após remover um elemento da instância de CollectionBase.Performs additional custom processes after removing an element from the CollectionBase instance.

OnSet(Int32, Object, Object) OnSet(Int32, Object, Object) OnSet(Int32, Object, Object) OnSet(Int32, Object, Object)

Executa processos personalizados adicionais antes de definir um valor na instância CollectionBase.Performs additional custom processes before setting a value in the CollectionBase instance.

OnSetComplete(Int32, Object, Object) OnSetComplete(Int32, Object, Object) OnSetComplete(Int32, Object, Object) OnSetComplete(Int32, Object, Object)

Executa processos personalizados adicionais após configurar um valor na instância de CollectionBase.Performs additional custom processes after setting a value in the CollectionBase instance.

OnValidate(Object) OnValidate(Object) OnValidate(Object) OnValidate(Object)

Executa processos personalizados adicionais ao validar um valor.Performs additional custom processes when validating a value.

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

Remove o elemento no índice especificado da instância CollectionBase.Removes the element at the specified index of the CollectionBase instance. Este método não é substituível.This method is not overridable.

ToString() ToString() ToString() ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Inherited from Object)

Implantações explícitas de interface

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

Copia todo o CollectionBase em um Array unidimensional compatível, começando no índice especificado da matriz de destino.Copies the entire CollectionBase to a compatible one-dimensional Array, starting at the specified index of the target array.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

Obtém um valor que indica se o acesso à CollectionBase é sincronizado (thread-safe).Gets a value indicating whether access to the CollectionBase is synchronized (thread safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao CollectionBase.Gets an object that can be used to synchronize access to the CollectionBase.

IList.Add(Object) IList.Add(Object) IList.Add(Object) IList.Add(Object)

Adiciona um objeto ao final do CollectionBase.Adds an object to the end of the CollectionBase.

IList.Contains(Object) IList.Contains(Object) IList.Contains(Object) IList.Contains(Object)

Determina se o CollectionBase contém um elemento específico.Determines whether the CollectionBase contains a specific element.

IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object)

Pesquisa o Object especificado e retorna o índice de base zero da primeira ocorrência dentro de todo o CollectionBase.Searches for the specified Object and returns the zero-based index of the first occurrence within the entire CollectionBase.

IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object)

Insere um elemento no CollectionBase, no índice especificado.Inserts an element into the CollectionBase at the specified index.

IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize

Obtém um valor que indica se o CollectionBase tem um tamanho fixo.Gets a value indicating whether the CollectionBase has a fixed size.

IList.IsReadOnly IList.IsReadOnly IList.IsReadOnly IList.IsReadOnly

Obtém um valor que indica se o CollectionBase é somente leitura.Gets a value indicating whether the CollectionBase is read-only.

IList.Item[Int32] IList.Item[Int32] IList.Item[Int32] IList.Item[Int32]

Obtém ou define o elemento no índice especificado.Gets or sets the element at the specified index.

IList.Remove(Object) IList.Remove(Object) IList.Remove(Object) IList.Remove(Object)

Remove a primeira ocorrência de um objeto específico do CollectionBase.Removes the first occurrence of a specific object from the CollectionBase.

Métodos de Extensão

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) 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) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) 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) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) 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 thread-safe.Any instance members are not guaranteed to be thread safe.

Essa implementação não fornece um wrapper sincronizado (thread-safe) para CollectionBaseuma, mas classes derivadas podem criar suas próprias versões sincronizadas CollectionBase do usando SyncRoot a propriedade.This implementation does not provide a synchronized (thread safe) wrapper for a CollectionBase, but derived classes can create their own synchronized versions of the CollectionBase using the SyncRoot property.

A enumeração por meio de uma coleção é intrinsecamente não um procedimento de thread seguro.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.

Veja também