NameObjectCollectionBase Classe

Definição

Fornece a abstract classe base para uma coleção de chaves e String valores associados Object que podem ser acessados com a chave ou com o índice.

public ref class NameObjectCollectionBase abstract : System::Collections::ICollection
public ref class NameObjectCollectionBase abstract : System::Collections::ICollection, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public abstract class NameObjectCollectionBase : System.Collections.ICollection
[System.Serializable]
public abstract class NameObjectCollectionBase : System.Collections.ICollection, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
public abstract class NameObjectCollectionBase : System.Collections.ICollection, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type NameObjectCollectionBase = class
    interface ICollection
    interface IEnumerable
[<System.Serializable>]
type NameObjectCollectionBase = class
    interface ICollection
    interface IEnumerable
    interface ISerializable
    interface IDeserializationCallback
type NameObjectCollectionBase = class
    interface ICollection
    interface IEnumerable
    interface IDeserializationCallback
    interface ISerializable
Public MustInherit Class NameObjectCollectionBase
Implements ICollection
Public MustInherit Class NameObjectCollectionBase
Implements ICollection, IDeserializationCallback, ISerializable
Herança
NameObjectCollectionBase
Derivado
Atributos
Implementações

Exemplos

O exemplo de código a seguir mostra como implementar e usar a NameObjectCollectionBase classe.

using System;
using System.Collections;
using System.Collections.Specialized;

public class MyCollection : NameObjectCollectionBase
{
   // Creates an empty collection.
   public MyCollection()  {
   }

   // Adds elements from an IDictionary into the new collection.
   public MyCollection( IDictionary d, Boolean bReadOnly )  {
      foreach ( DictionaryEntry de in d )  {
         this.BaseAdd( (String) de.Key, de.Value );
      }
      this.IsReadOnly = bReadOnly;
   }

   // Gets a key-and-value pair (DictionaryEntry) using an index.
   public DictionaryEntry this[ int index ]  {
      get  {
          return ( new DictionaryEntry(
              this.BaseGetKey(index), this.BaseGet(index) ) );
      }
   }

   // Gets or sets the value associated with the specified key.
   public Object this[ String key ]  {
      get  {
         return( this.BaseGet( key ) );
      }
      set  {
         this.BaseSet( key, value );
      }
   }

   // Gets a String array that contains all the keys in the collection.
   public String[] AllKeys  {
      get  {
         return( this.BaseGetAllKeys() );
      }
   }

   // Gets an Object array that contains all the values in the collection.
   public Array AllValues  {
      get  {
         return( this.BaseGetAllValues() );
      }
   }

   // Gets a String array that contains all the values in the collection.
   public String[] AllStringValues  {
      get  {
         return( (String[]) this.BaseGetAllValues( typeof( string ) ));
      }
   }

   // Gets a value indicating if the collection contains keys that are not null.
   public Boolean HasKeys  {
      get  {
         return( this.BaseHasKeys() );
      }
   }

   // Adds an entry to the collection.
   public void Add( String key, Object value )  {
      this.BaseAdd( key, value );
   }

   // Removes an entry with the specified key from the collection.
   public void Remove( String key )  {
      this.BaseRemove( key );
   }

   // Removes an entry in the specified index from the collection.
   public void Remove( int index )  {
      this.BaseRemoveAt( index );
   }

   // Clears all the elements in the collection.
   public void Clear()  {
      this.BaseClear();
   }
}

public class SamplesNameObjectCollectionBase  {

   public static void Main()  {

      // Creates and initializes a new MyCollection that is read-only.
      IDictionary d = new ListDictionary();
      d.Add( "red", "apple" );
      d.Add( "yellow", "banana" );
      d.Add( "green", "pear" );
      MyCollection myROCol = new MyCollection( d, true );

      // Tries to add a new item.
      try  {
         myROCol.Add( "blue", "sky" );
      }
      catch ( NotSupportedException e )  {
         Console.WriteLine( e.ToString() );
      }

      // Displays the keys and values of the MyCollection.
      Console.WriteLine( "Read-Only Collection:" );
      PrintKeysAndValues( myROCol );

      // Creates and initializes an empty MyCollection that is writable.
      MyCollection myRWCol = new MyCollection();

      // Adds new items to the collection.
      myRWCol.Add( "purple", "grape" );
      myRWCol.Add( "orange", "tangerine" );
      myRWCol.Add( "black", "berries" );
      Console.WriteLine( "Writable Collection (after adding values):" );
      PrintKeysAndValues( myRWCol );

      // Changes the value of one element.
      myRWCol["orange"] = "grapefruit";
      Console.WriteLine( "Writable Collection (after changing one value):" );
      PrintKeysAndValues( myRWCol );

      // Removes one item from the collection.
      myRWCol.Remove( "black" );
      Console.WriteLine( "Writable Collection (after removing one value):" );
      PrintKeysAndValues( myRWCol );

      // Removes all elements from the collection.
      myRWCol.Clear();
      Console.WriteLine( "Writable Collection (after clearing the collection):" );
      PrintKeysAndValues( myRWCol );
   }

   // Prints the indexes, keys, and values.
   public static void PrintKeysAndValues( MyCollection myCol )  {
      for ( int i = 0; i < myCol.Count; i++ )  {
         Console.WriteLine( "[{0}] : {1}, {2}", i, myCol[i].Key, myCol[i].Value );
      }
   }

   // Prints the keys and values using AllKeys.
   public static void PrintKeysAndValues2( MyCollection myCol )  {
      foreach ( String s in myCol.AllKeys )  {
         Console.WriteLine( "{0}, {1}", s, myCol[s] );
      }
   }
}


/*
This code produces the following output.

System.NotSupportedException: Collection is read-only.
   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
   at SamplesNameObjectCollectionBase.Main()
Read-Only Collection:
[0] : red, apple
[1] : yellow, banana
[2] : green, pear
Writable Collection (after adding values):
[0] : purple, grape
[1] : orange, tangerine
[2] : black, berries
Writable Collection (after changing one value):
[0] : purple, grape
[1] : orange, grapefruit
[2] : black, berries
Writable Collection (after removing one value):
[0] : purple, grape
[1] : orange, grapefruit
Writable Collection (after clearing the collection):

*/
Imports System.Collections
Imports System.Collections.Specialized

Public Class MyCollection
   Inherits NameObjectCollectionBase

   ' Creates an empty collection.
   Public Sub New()
   End Sub

   ' Adds elements from an IDictionary into the new collection.
   Public Sub New(d As IDictionary, bReadOnly As Boolean)
      Dim de As DictionaryEntry
      For Each de In  d
         Me.BaseAdd(CType(de.Key, String), de.Value)
      Next de
      Me.IsReadOnly = bReadOnly
   End Sub

   ' Gets a key-and-value pair (DictionaryEntry) using an index.
   Default Public ReadOnly Property Item(index As Integer) As DictionaryEntry
      Get
            return new DictionaryEntry( _
                me.BaseGetKey(index), me.BaseGet(index) )
      End Get
   End Property

   ' Gets or sets the value associated with the specified key.
   Default Public Property Item(key As String) As Object
      Get
         Return Me.BaseGet(key)
      End Get
      Set
         Me.BaseSet(key, value)
      End Set
   End Property

   ' Gets a String array that contains all the keys in the collection.
   Public ReadOnly Property AllKeys() As String()
      Get
         Return Me.BaseGetAllKeys()
      End Get
   End Property

   ' Gets an Object array that contains all the values in the collection.
   Public ReadOnly Property AllValues() As Array
      Get
         Return Me.BaseGetAllValues()
      End Get
   End Property

   ' Gets a String array that contains all the values in the collection.
   Public ReadOnly Property AllStringValues() As String()
      Get
         Return CType(Me.BaseGetAllValues(GetType(String)), String())
      End Get
   End Property

   ' Gets a value indicating if the collection contains keys that are not null.
   Public ReadOnly Property HasKeys() As Boolean
      Get
         Return Me.BaseHasKeys()
      End Get
   End Property

   ' Adds an entry to the collection.
   Public Sub Add(key As String, value As Object)
      Me.BaseAdd(key, value)
   End Sub

   ' Removes an entry with the specified key from the collection.
   Overloads Public Sub Remove(key As String)
      Me.BaseRemove(key)
   End Sub

   ' Removes an entry in the specified index from the collection.
   Overloads Public Sub Remove(index As Integer)
      Me.BaseRemoveAt(index)
   End Sub

   ' Clears all the elements in the collection.
   Public Sub Clear()
      Me.BaseClear()
   End Sub

End Class


Public Class SamplesNameObjectCollectionBase   

   Public Shared Sub Main()

      ' Creates and initializes a new MyCollection that is read-only.
      Dim d As New ListDictionary()
      d.Add("red", "apple")
      d.Add("yellow", "banana")
      d.Add("green", "pear")
      Dim myROCol As New MyCollection(d, True)

      ' Tries to add a new item.
      Try
         myROCol.Add("blue", "sky")
      Catch e As NotSupportedException
         Console.WriteLine(e.ToString())
      End Try

      ' Displays the keys and values of the MyCollection.
      Console.WriteLine("Read-Only Collection:")
      PrintKeysAndValues(myROCol)

      ' Creates and initializes an empty MyCollection that is writable.
      Dim myRWCol As New MyCollection()

      ' Adds new items to the collection.
      myRWCol.Add("purple", "grape")
      myRWCol.Add("orange", "tangerine")
      myRWCol.Add("black", "berries")
      Console.WriteLine("Writable Collection (after adding values):")
      PrintKeysAndValues(myRWCol)

      ' Changes the value of one element.
      myRWCol("orange") = "grapefruit"
      Console.WriteLine("Writable Collection (after changing one value):")
      PrintKeysAndValues(myRWCol)

      ' Removes one item from the collection.
      myRWCol.Remove("black")
      Console.WriteLine("Writable Collection (after removing one value):")
      PrintKeysAndValues(myRWCol)

      ' Removes all elements from the collection.
      myRWCol.Clear()
      Console.WriteLine("Writable Collection (after clearing the collection):")
      PrintKeysAndValues(myRWCol)

   End Sub

   ' Prints the indexes, keys, and values.
   Public Shared Sub PrintKeysAndValues(myCol As MyCollection)
      Dim i As Integer
      For i = 0 To myCol.Count - 1
         Console.WriteLine("[{0}] : {1}, {2}", i, myCol(i).Key, myCol(i).Value)
      Next i
   End Sub

   ' Prints the keys and values using AllKeys.
   Public Shared Sub PrintKeysAndValues2(myCol As MyCollection)
      Dim s As String
      For Each s In  myCol.AllKeys
         Console.WriteLine("{0}, {1}", s, myCol(s))
      Next s
   End Sub

End Class


'This code produces the following output.
'
'System.NotSupportedException: Collection is read-only.
'   at System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String name, Object value)
'   at SamplesNameObjectCollectionBase.Main()
'Read-Only Collection:
'[0] : red, apple
'[1] : yellow, banana
'[2] : green, pear
'Writable Collection (after adding values):
'[0] : purple, grape
'[1] : orange, tangerine
'[2] : black, berries
'Writable Collection (after changing one value):
'[0] : purple, grape
'[1] : orange, grapefruit
'[2] : black, berries
'Writable Collection (after removing one value):
'[0] : purple, grape
'[1] : orange, grapefruit
'Writable Collection (after clearing the collection):

Comentários

A estrutura subjacente para essa classe é uma tabela de hash.

Cada elemento é um par chave/valor.

A capacidade de um NameObjectCollectionBase é o número de elementos que podem NameObjectCollectionBase conter. À medida que os elementos são adicionados a um NameObjectCollectionBase, a capacidade é automaticamente aumentada conforme necessário por meio da realocação.

O provedor de código hash distribui códigos de hash para chaves na NameObjectCollectionBase instância. O provedor de código hash padrão é o CaseInsensitiveHashCodeProvider.

O comparador determina se duas chaves são iguais. O comparador padrão é o CaseInsensitiveComparer.

No .NET Framework versão 1.0, essa classe usa comparações de cadeias de caracteres sensíveis à cultura. No entanto, no .NET Framework versão 1.1 e posterior, essa classe usa CultureInfo.InvariantCulture ao comparar cadeias de caracteres. Para obter mais informações sobre como a cultura afeta comparações e classificação, consulte Executar operações de cadeia de caracteres Culture-Insensitive.

null é permitido como uma chave ou como um valor.

Caution

O BaseGet método não distingue entre null o que é retornado porque a chave especificada não foi encontrada e null retornada porque o valor associado à chave é null.

Construtores

Nome Description
NameObjectCollectionBase()

Inicializa uma nova instância da NameObjectCollectionBase classe que está vazia.

NameObjectCollectionBase(IEqualityComparer)

Inicializa uma nova instância da NameObjectCollectionBase classe que está vazia, tem a capacidade inicial padrão e usa o objeto especificado IEqualityComparer .

NameObjectCollectionBase(IHashCodeProvider, IComparer)
Obsoleto.

Inicializa uma nova instância da NameObjectCollectionBase classe que está vazia, tem a capacidade inicial padrão e usa o provedor de código hash especificado e o comparador especificado.

NameObjectCollectionBase(Int32, IEqualityComparer)

Inicializa uma nova instância da NameObjectCollectionBase classe que está vazia, tem a capacidade inicial especificada e usa o objeto especificado IEqualityComparer .

NameObjectCollectionBase(Int32, IHashCodeProvider, IComparer)
Obsoleto.

Inicializa uma nova instância da NameObjectCollectionBase classe que está vazia, tem a capacidade inicial especificada e usa o provedor de código hash especificado e o comparador especificado.

NameObjectCollectionBase(Int32)

Inicializa uma nova instância da NameObjectCollectionBase classe que está vazia, tem a capacidade inicial especificada e usa o provedor de código hash padrão e o comparador padrão.

NameObjectCollectionBase(SerializationInfo, StreamingContext)

Inicializa uma nova instância da NameObjectCollectionBase classe que é serializável e usa o especificado SerializationInfo e StreamingContext.

Propriedades

Nome Description
Count

Obtém o número de pares chave/valor contidos na NameObjectCollectionBase instância.

IsReadOnly

Obtém ou define um valor que indica se a NameObjectCollectionBase instância é somente leitura.

Keys

Obtém uma NameObjectCollectionBase.KeysCollection instância que contém todas as chaves na NameObjectCollectionBase instância.

Métodos

Nome Description
BaseAdd(String, Object)

Adiciona uma entrada com a chave e o valor especificados à NameObjectCollectionBase instância.

BaseClear()

Remove todas as entradas da NameObjectCollectionBase instância.

BaseGet(Int32)

Obtém o valor da entrada no índice especificado da NameObjectCollectionBase instância.

BaseGet(String)

Obtém o valor da primeira entrada com a chave especificada da NameObjectCollectionBase instância.

BaseGetAllKeys()

Retorna uma String matriz que contém todas as chaves na NameObjectCollectionBase instância.

BaseGetAllValues()

Retorna uma Object matriz que contém todos os valores na NameObjectCollectionBase instância.

BaseGetAllValues(Type)

Retorna uma matriz do tipo especificado que contém todos os valores na NameObjectCollectionBase instância.

BaseGetKey(Int32)

Obtém a chave da entrada no índice especificado da NameObjectCollectionBase instância.

BaseHasKeys()

Obtém um valor que indica se a NameObjectCollectionBase instância contém entradas cujas chaves não nullsão .

BaseRemove(String)

Remove as entradas com a chave especificada da NameObjectCollectionBase instância.

BaseRemoveAt(Int32)

Remove a entrada no índice especificado da NameObjectCollectionBase instância.

BaseSet(Int32, Object)

Define o valor da entrada no índice especificado da NameObjectCollectionBase instância.

BaseSet(String, Object)

Define o valor da primeira entrada com a chave especificada na NameObjectCollectionBase instância, se encontrada; caso contrário, adiciona uma entrada com a chave e o valor especificados na NameObjectCollectionBase instância.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetEnumerator()

Retorna um enumerador que itera por meio do NameObjectCollectionBase.

GetHashCode()

Serve como a função hash predefinida.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implementa a ISerializable interface e retorna os dados necessários para serializar a NameObjectCollectionBase instância.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do Objectatual.

(Herdado de Object)
OnDeserialization(Object)

Implementa a ISerializable interface e gera o evento de desserialização quando a desserialização é concluída.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

Nome Description
ICollection.CopyTo(Array, Int32)

Copia o todo NameObjectCollectionBase para um unidimensional Arraycompatível, começando no índice especificado da matriz de destino.

ICollection.IsSynchronized

Obtém um valor que indica se o NameObjectCollectionBase acesso ao objeto é sincronizado (thread safe).

ICollection.SyncRoot

Obtém um objeto que pode ser usado para sincronizar o acesso ao NameObjectCollectionBase objeto.

Métodos de Extensão

Nome Description
AsParallel(IEnumerable)

Habilita a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable em um IQueryable.

Cast<TResult>(IEnumerable)

Converte os elementos de um IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

Filtra os elementos de um IEnumerable com base em um tipo especificado.

Aplica-se a

Acesso thread-safe

Membros estáticos públicos (Shared no Visual Basic) desse tipo são thread safe. Não há garantia de que quaisquer membros de instância sejam thread-safe.

Essa implementação não fornece um wrapper sincronizado (thread safe) para umNameObjectCollectionBase, mas classes derivadas podem criar suas próprias versões sincronizadas da NameObjectCollectionBase propriedade usando.SyncRoot

Enumerar por meio de uma coleção não é intrinsecamente um procedimento seguro de thread. Mesmo quando uma coleção é sincronizada, outros threads ainda podem modificar a coleção, o que faz com que o enumerador gere uma exceção. Para garantir a segurança do thread durante a enumeração, você pode bloquear a coleção durante toda a enumeração ou capturar as exceções resultantes de alterações feitas por outros threads.

Confira também