NameObjectCollectionBase Classe

Definição

Fornece a abstract classe base para uma coleção de chaves e Object valores associados String que podem ser acedidos tanto com a chave como 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 seguinte exemplo de código 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):

Observações

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

Cada elemento é um par chave/valor.

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

O fornecedor do código hash dispensa códigos hash para chaves na NameObjectCollectionBase instância. O fornecedor de código hash por defeito é o CaseInsensitiveHashCodeProvider.

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

No .NET Framework versão 1.0, esta classe utiliza comparações de cadeias sensíveis à cultura. No entanto, na versão 1.1 do Framework .NET e posteriores, esta classe usa CultureInfo.InvariantCulture ao comparar cadeias. Para mais informações sobre como a cultura afeta as comparações e a ordenação, veja Executar Culture-Insensitive Operações de Strings.

null é permitido como chave ou como valor.

Atenção

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

Construtores

Name 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 utiliza o fornecedor 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 utiliza o fornecedor 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 fornecedor 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 os especificados SerializationInfo e StreamingContext.

Propriedades

Name Description
Count

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

IsReadOnly

Recebe ou define um valor que indica se a NameObjectCollectionBase instância é apenas leitura.

Keys

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

Métodos

Name 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()

Devolve um String array que contém todas as chaves da NameObjectCollectionBase instância.

BaseGetAllValues()

Devolve um Object array que contém todos os valores da NameObjectCollectionBase instância.

BaseGetAllValues(Type)

Devolve um array do tipo especificado que contém todos os valores da 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 valor especificados à NameObjectCollectionBase instância.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetEnumerator()

Devolve um enumerador que itera através do NameObjectCollectionBase.

GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetObjectData(SerializationInfo, StreamingContext)

Implementa a ISerializable interface e devolve 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 atual Object.

(Herdado de Object)
OnDeserialization(Object)

Implementa a ISerializable interface e levanta o evento de desserialização quando a desserialização está concluída.

ToString()

Devolve uma cadeia que representa o objeto atual.

(Herdado de Object)

Implementações de Interface Explícita

Name Description
ICollection.CopyTo(Array, Int32)

Copia a totalidade NameObjectCollectionBase para uma unidimensional Arraycompatível , começando no índice especificado do array alvo.

ICollection.IsSynchronized

Recebe um valor que indica se o acesso ao NameObjectCollectionBase objeto está sincronizado (thread safe).

ICollection.SyncRoot

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

Métodos da Extensão

Name Description
AsParallel(IEnumerable)

Permite a paralelização de uma consulta.

AsQueryable(IEnumerable)

Converte um IEnumerable para um IQueryable.

Cast<TResult>(IEnumerable)

Conjura os elementos de an IEnumerable para o tipo especificado.

OfType<TResult>(IEnumerable)

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

Aplica-se a

Segurança de Thread

Os membros estáticos públicos (Shared em Visual Basic) deste tipo são seguros para threads. Qualquer membro de instância não é garantido que seja seguro contra threads.

Esta implementação não fornece um wrapper sincronizado (seguro para threads) para um NameObjectCollectionBase, mas classes derivadas podem criar as suas próprias versões sincronizadas do NameObjectCollectionBase usando a SyncRoot propriedade.

Enumerar através de uma coleção não é intrinsecamente um procedimento seguro para threads. Mesmo quando uma coleção está sincronizada, outros threads ainda podem modificar a coleção, o que faz com que o enumerador lance uma exceção. Para garantir a segurança dos threads durante a enumeração, pode bloquear a coleção durante toda a enumeração ou apanhar as exceções resultantes de alterações feitas por outros threads.

Ver também