DictionaryBase Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Fornece a abstract classe base para uma coleção fortemente tipada de pares chave/valor.
public ref class DictionaryBase abstract : System::Collections::IDictionary
public abstract class DictionaryBase : System.Collections.IDictionary
[System.Serializable]
public abstract class DictionaryBase : System.Collections.IDictionary
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class DictionaryBase : System.Collections.IDictionary
type DictionaryBase = class
interface ICollection
interface IEnumerable
interface IDictionary
[<System.Serializable>]
type DictionaryBase = class
interface IDictionary
interface ICollection
interface IEnumerable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type DictionaryBase = class
interface IDictionary
interface ICollection
interface IEnumerable
Public MustInherit Class DictionaryBase
Implements IDictionary
- Herança
-
DictionaryBase
- Derivado
- Atributos
- Implementações
Exemplos
O exemplo de código seguinte implementa a DictionaryBase classe e usa essa implementação para criar um dicionário de String chaves e valores com a Length de 5 caracteres ou menos.
using System;
using System.Collections;
public class ShortStringDictionary : DictionaryBase {
public String this[ String key ] {
get {
return( (String) Dictionary[key] );
}
set {
Dictionary[key] = value;
}
}
public ICollection Keys {
get {
return( Dictionary.Keys );
}
}
public ICollection Values {
get {
return( Dictionary.Values );
}
}
public void Add( String key, String value ) {
Dictionary.Add( key, value );
}
public bool Contains( String key ) {
return( Dictionary.Contains( key ) );
}
public void Remove( String key ) {
Dictionary.Remove( key );
}
protected override void OnInsert( Object key, Object value ) {
if ( key.GetType() != typeof(System.String) )
{
throw new ArgumentException( "key must be of type String.", "key" );
}
else {
String strKey = (String) key;
if ( strKey.Length > 5 )
throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
}
if ( value.GetType() != typeof(System.String) )
{
throw new ArgumentException( "value must be of type String.", "value" );
}
else {
String strValue = (String) value;
if ( strValue.Length > 5 )
throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
}
}
protected override void OnRemove( Object key, Object value ) {
if ( key.GetType() != typeof(System.String) )
{
throw new ArgumentException( "key must be of type String.", "key" );
}
else {
String strKey = (String) key;
if ( strKey.Length > 5 )
throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
}
}
protected override void OnSet( Object key, Object oldValue, Object newValue ) {
if ( key.GetType() != typeof(System.String) )
{
throw new ArgumentException( "key must be of type String.", "key" );
}
else {
String strKey = (String) key;
if ( strKey.Length > 5 )
throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
}
if ( newValue.GetType() != typeof(System.String) )
{
throw new ArgumentException( "newValue must be of type String.", "newValue" );
}
else {
String strValue = (String) newValue;
if ( strValue.Length > 5 )
throw new ArgumentException( "newValue must be no more than 5 characters in length.", "newValue" );
}
}
protected override void OnValidate( Object key, Object value ) {
if ( key.GetType() != typeof(System.String) )
{
throw new ArgumentException( "key must be of type String.", "key" );
}
else {
String strKey = (String) key;
if ( strKey.Length > 5 )
throw new ArgumentException( "key must be no more than 5 characters in length.", "key" );
}
if ( value.GetType() != typeof(System.String) )
{
throw new ArgumentException( "value must be of type String.", "value" );
}
else {
String strValue = (String) value;
if ( strValue.Length > 5 )
throw new ArgumentException( "value must be no more than 5 characters in length.", "value" );
}
}
}
public class SamplesDictionaryBase {
public static void Main() {
// Creates and initializes a new DictionaryBase.
ShortStringDictionary mySSC = new ShortStringDictionary();
// Adds elements to the collection.
mySSC.Add( "One", "a" );
mySSC.Add( "Two", "ab" );
mySSC.Add( "Three", "abc" );
mySSC.Add( "Four", "abcd" );
mySSC.Add( "Five", "abcde" );
// Display the contents of the collection using foreach. This is the preferred method.
Console.WriteLine( "Contents of the collection (using foreach):" );
PrintKeysAndValues1( mySSC );
// Display the contents of the collection using the enumerator.
Console.WriteLine( "Contents of the collection (using enumerator):" );
PrintKeysAndValues2( mySSC );
// Display the contents of the collection using the Keys property and the Item property.
Console.WriteLine( "Initial contents of the collection (using Keys and Item):" );
PrintKeysAndValues3( mySSC );
// Tries to add a value that is too long.
try {
mySSC.Add( "Ten", "abcdefghij" );
}
catch ( ArgumentException e ) {
Console.WriteLine( e.ToString() );
}
// Tries to add a key that is too long.
try {
mySSC.Add( "Eleven", "ijk" );
}
catch ( ArgumentException e ) {
Console.WriteLine( e.ToString() );
}
Console.WriteLine();
// Searches the collection with Contains.
Console.WriteLine( "Contains \"Three\": {0}", mySSC.Contains( "Three" ) );
Console.WriteLine( "Contains \"Twelve\": {0}", mySSC.Contains( "Twelve" ) );
Console.WriteLine();
// Removes an element from the collection.
mySSC.Remove( "Two" );
// Displays the contents of the collection.
Console.WriteLine( "After removing \"Two\":" );
PrintKeysAndValues1( mySSC );
}
// 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 PrintKeysAndValues1( ShortStringDictionary myCol ) {
foreach ( DictionaryEntry myDE in myCol )
Console.WriteLine( " {0,-5} : {1}", myDE.Key, myDE.Value );
Console.WriteLine();
}
// Uses the enumerator.
// NOTE: The foreach statement is the preferred way of enumerating the contents of a collection.
public static void PrintKeysAndValues2( ShortStringDictionary myCol ) {
DictionaryEntry myDE;
System.Collections.IEnumerator myEnumerator = myCol.GetEnumerator();
while ( myEnumerator.MoveNext() )
if ( myEnumerator.Current != null ) {
myDE = (DictionaryEntry) myEnumerator.Current;
Console.WriteLine( " {0,-5} : {1}", myDE.Key, myDE.Value );
}
Console.WriteLine();
}
// Uses the Keys property and the Item property.
public static void PrintKeysAndValues3( ShortStringDictionary myCol ) {
ICollection myKeys = myCol.Keys;
foreach ( String k in myKeys )
Console.WriteLine( " {0,-5} : {1}", k, myCol[k] );
Console.WriteLine();
}
}
/*
This code produces the following output.
Contents of the collection (using foreach):
Three : abc
Five : abcde
Two : ab
One : a
Four : abcd
Contents of the collection (using enumerator):
Three : abc
Five : abcde
Two : ab
One : a
Four : abcd
Initial contents of the collection (using Keys and Item):
Three : abc
Five : abcde
Two : ab
One : a
Four : abcd
System.ArgumentException: value must be no more than 5 characters in length.
Parameter name: value
at ShortStringDictionary.OnValidate(Object key, Object value)
at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
at SamplesDictionaryBase.Main()
System.ArgumentException: key must be no more than 5 characters in length.
Parameter name: key
at ShortStringDictionary.OnValidate(Object key, Object value)
at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
at SamplesDictionaryBase.Main()
Contains "Three": True
Contains "Twelve": False
After removing "Two":
Three : abc
Five : abcde
One : a
Four : abcd
*/
Imports System.Collections
Public Class ShortStringDictionary
Inherits DictionaryBase
Default Public Property Item(key As String) As String
Get
Return CType(Dictionary(key), String)
End Get
Set
Dictionary(key) = value
End Set
End Property
Public ReadOnly Property Keys() As ICollection
Get
Return Dictionary.Keys
End Get
End Property
Public ReadOnly Property Values() As ICollection
Get
Return Dictionary.Values
End Get
End Property
Public Sub Add(key As String, value As String)
Dictionary.Add(key, value)
End Sub
Public Function Contains(key As String) As Boolean
Return Dictionary.Contains(key)
End Function 'Contains
Public Sub Remove(key As String)
Dictionary.Remove(key)
End Sub
Protected Overrides Sub OnInsert(key As Object, value As Object)
If Not GetType(System.String).IsAssignableFrom(key.GetType()) Then
Throw New ArgumentException("key must be of type String.", "key")
Else
Dim strKey As String = CType(key, String)
If strKey.Length > 5 Then
Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
End If
End If
If Not GetType(System.String).IsAssignableFrom(value.GetType()) Then
Throw New ArgumentException("value must be of type String.", "value")
Else
Dim strValue As String = CType(value, String)
If strValue.Length > 5 Then
Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
End If
End If
End Sub
Protected Overrides Sub OnRemove(key As Object, value As Object)
If Not GetType(System.String).IsAssignableFrom(key.GetType()) Then
Throw New ArgumentException("key must be of type String.", "key")
Else
Dim strKey As String = CType(key, String)
If strKey.Length > 5 Then
Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
End If
End If
End Sub
Protected Overrides Sub OnSet(key As Object, oldValue As Object, newValue As Object)
If Not GetType(System.String).IsAssignableFrom(key.GetType()) Then
Throw New ArgumentException("key must be of type String.", "key")
Else
Dim strKey As String = CType(key, String)
If strKey.Length > 5 Then
Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
End If
End If
If Not GetType(System.String).IsAssignableFrom(newValue.GetType()) Then
Throw New ArgumentException("newValue must be of type String.", "newValue")
Else
Dim strValue As String = CType(newValue, String)
If strValue.Length > 5 Then
Throw New ArgumentException("newValue must be no more than 5 characters in length.", "newValue")
End If
End If
End Sub
Protected Overrides Sub OnValidate(key As Object, value As Object)
If Not GetType(System.String).IsAssignableFrom(key.GetType()) Then
Throw New ArgumentException("key must be of type String.", "key")
Else
Dim strKey As String = CType(key, String)
If strKey.Length > 5 Then
Throw New ArgumentException("key must be no more than 5 characters in length.", "key")
End If
End If
If Not GetType(System.String).IsAssignableFrom(value.GetType()) Then
Throw New ArgumentException("value must be of type String.", "value")
Else
Dim strValue As String = CType(value, String)
If strValue.Length > 5 Then
Throw New ArgumentException("value must be no more than 5 characters in length.", "value")
End If
End If
End Sub
End Class
Public Class SamplesDictionaryBase
Public Shared Sub Main()
' Creates and initializes a new DictionaryBase.
Dim mySSC As New ShortStringDictionary()
' Adds elements to the collection.
mySSC.Add("One", "a")
mySSC.Add("Two", "ab")
mySSC.Add("Three", "abc")
mySSC.Add("Four", "abcd")
mySSC.Add("Five", "abcde")
' Display the contents of the collection using For Each. This is the preferred method.
Console.WriteLine("Contents of the collection (using For Each):")
PrintKeysAndValues1(mySSC)
' Display the contents of the collection using the enumerator.
Console.WriteLine("Contents of the collection (using enumerator):")
PrintKeysAndValues2(mySSC)
' Display the contents of the collection using the Keys property and the Item property.
Console.WriteLine("Initial contents of the collection (using Keys and Item):")
PrintKeysAndValues3(mySSC)
' Tries to add a value that is too long.
Try
mySSC.Add("Ten", "abcdefghij")
Catch e As ArgumentException
Console.WriteLine(e.ToString())
End Try
' Tries to add a key that is too long.
Try
mySSC.Add("Eleven", "ijk")
Catch e As ArgumentException
Console.WriteLine(e.ToString())
End Try
Console.WriteLine()
' Searches the collection with Contains.
Console.WriteLine("Contains ""Three"": {0}", mySSC.Contains("Three"))
Console.WriteLine("Contains ""Twelve"": {0}", mySSC.Contains("Twelve"))
Console.WriteLine()
' Removes an element from the collection.
mySSC.Remove("Two")
' Displays the contents of the collection.
Console.WriteLine("After removing ""Two"":")
PrintKeysAndValues1(mySSC)
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 PrintKeysAndValues1(myCol As ShortStringDictionary)
Dim myDE As DictionaryEntry
For Each myDE In myCol
Console.WriteLine(" {0,-5} : {1}", myDE.Key, myDE.Value)
Next myDE
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 PrintKeysAndValues2(myCol As ShortStringDictionary)
Dim myDE As DictionaryEntry
Dim myEnumerator As System.Collections.IEnumerator = myCol.GetEnumerator()
While myEnumerator.MoveNext()
If Not (myEnumerator.Current Is Nothing) Then
myDE = CType(myEnumerator.Current, DictionaryEntry)
Console.WriteLine(" {0,-5} : {1}", myDE.Key, myDE.Value)
End If
End While
Console.WriteLine()
End Sub
' Uses the Keys property and the Item property.
Public Shared Sub PrintKeysAndValues3(myCol As ShortStringDictionary)
Dim myKeys As ICollection = myCol.Keys
Dim k As String
For Each k In myKeys
Console.WriteLine(" {0,-5} : {1}", k, myCol(k))
Next k
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'Contents of the collection (using For Each):
' Three : abc
' Five : abcde
' Two : ab
' One : a
' Four : abcd
'
'Contents of the collection (using enumerator):
' Three : abc
' Five : abcde
' Two : ab
' One : a
' Four : abcd
'
'Initial contents of the collection (using Keys and Item):
' Three : abc
' Five : abcde
' Two : ab
' One : a
' Four : abcd
'
'System.ArgumentException: value must be no more than 5 characters in length.
'Parameter name: value
' at ShortStringDictionary.OnValidate(Object key, Object value)
' at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
' at SamplesDictionaryBase.Main()
'System.ArgumentException: key must be no more than 5 characters in length.
'Parameter name: key
' at ShortStringDictionary.OnValidate(Object key, Object value)
' at System.Collections.DictionaryBase.System.Collections.IDictionary.Add(Object key, Object value)
' at SamplesDictionaryBase.Main()
'
'Contains "Three": True
'Contains "Twelve": False
'
'After removing "Two":
' Three : abc
' Five : abcde
' One : a
' Four : abcd
Observações
Importante
Não recomendamos que uses a DictionaryBase disciplina para novos desenvolvimentos. Em vez disso, recomendamos que use o genérico Dictionary<TKey,TValue> ou KeyedCollection<TKey,TItem> a classe . Para mais informações, veja Não devem ser usadas coleções não genéricas em GitHub.
A instrução C# foreach e a sentença Visual Basic For Each retornam um objeto do tipo dos elementos da coleção. Como cada elemento de é DictionaryBase um par chave/valor, o tipo de elemento não é o tipo da chave nem o tipo do valor. Em vez disso, o tipo de elemento é DictionaryEntry.
A foreach declaração é um wrapper em torno do enumerador, que só permite ler a partir da coleção, não escrever para.
Note
Como as chaves podem ser herdadas e o seu comportamento alterado, a sua singularidade absoluta não pode ser garantida por comparações usando o Equals método.
Notas para Implementadores
Esta classe base é fornecida para facilitar aos implementadores a criação de uma coleção personalizada fortemente tipada. Os implementadores são incentivados a expandir esta classe base em vez de criarem a sua própria.
Os membros desta classe base estão protegidos e destinam-se a ser usados apenas através de uma classe derivada.
Construtores
| Name | Description |
|---|---|
| DictionaryBase() |
Inicializa uma nova instância da DictionaryBase classe. |
Propriedades
| Name | Description |
|---|---|
| Count |
Obtém o número de elementos contidos na DictionaryBase instância. |
| Dictionary |
Obtém a lista de elementos contidos na DictionaryBase instância. |
| InnerHashtable |
Obtém a lista de elementos contidos na DictionaryBase instância. |
Métodos
| Name | Description |
|---|---|
| Clear() |
Limpa o conteúdo da DictionaryBase instância. |
| CopyTo(Array, Int32) |
Copia os DictionaryBase elementos para um índice unidimensional Array no índice especificado. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetEnumerator() |
Retorna um IDictionaryEnumerator que itera pela DictionaryBase instância. |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| OnClear() |
Realiza processos personalizados adicionais antes de limpar o conteúdo da DictionaryBase instância. |
| OnClearComplete() |
Realiza processos personalizados adicionais após limpar o conteúdo da DictionaryBase instância. |
| OnGet(Object, Object) |
Obtém o elemento com a chave e valor especificados na DictionaryBase instância. |
| OnInsert(Object, Object) |
Realiza processos personalizados adicionais antes de inserir um novo elemento na DictionaryBase instância. |
| OnInsertComplete(Object, Object) |
Executa processos personalizados adicionais após inserir um novo elemento na DictionaryBase instância. |
| OnRemove(Object, Object) |
Realiza processos personalizados adicionais antes de remover um elemento da DictionaryBase instância. |
| OnRemoveComplete(Object, Object) |
Executa processos personalizados adicionais após remover um elemento da DictionaryBase instância. |
| OnSet(Object, Object, Object) |
Realiza processos personalizados adicionais antes de definir um valor na DictionaryBase instância. |
| OnSetComplete(Object, Object, Object) |
Executa processos personalizados adicionais após definir um valor na DictionaryBase instância. |
| OnValidate(Object, Object) |
Executa processos personalizados adicionais ao validar o elemento com a chave e valor especificados. |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
Implementações de Interface Explícita
| Name | Description |
|---|---|
| ICollection.IsSynchronized |
Recebe um valor que indica se o acesso a um DictionaryBase objeto está sincronizado (thread safe). |
| ICollection.SyncRoot |
Obtém um objeto que pode ser usado para sincronizar o acesso a um DictionaryBase objeto. |
| IDictionary.Add(Object, Object) |
Adiciona um elemento com a chave e valor especificados no DictionaryBase. |
| IDictionary.Contains(Object) |
Determina se o DictionaryBase contém uma chave específica. |
| IDictionary.IsFixedSize |
Obtém um valor que indica se um DictionaryBase objeto tem um tamanho fixo. |
| IDictionary.IsReadOnly |
Recebe um valor que indica se um DictionaryBase objeto é apenas de leitura. |
| IDictionary.Item[Object] |
Obtém ou define o valor associado à chave especificada. |
| IDictionary.Keys |
Obtém um ICollection objeto contendo as chaves no DictionaryBase objeto. |
| IDictionary.Remove(Object) |
Remove o elemento com a chave especificada da DictionaryBase. |
| IDictionary.Values |
Obtém um ICollection objeto contendo os valores do DictionaryBase objeto. |
| IEnumerable.GetEnumerator() |
Retorna um IEnumerator que itera através do DictionaryBase. |
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 (thread-safe) para um DictionaryBase, mas as classes derivadas podem criar as suas próprias versões sincronizadas do DictionaryBase 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.