DictionaryBase Klasa

Definicja

Udostępnia klasę abstract bazową dla silnie typizowanej kolekcji par klucz/wartość.

C#
public abstract class DictionaryBase : System.Collections.IDictionary
C#
[System.Serializable]
public abstract class DictionaryBase : System.Collections.IDictionary
C#
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class DictionaryBase : System.Collections.IDictionary
Dziedziczenie
DictionaryBase
Pochodne
Atrybuty
Implementuje

Przykłady

Poniższy przykład kodu implementuje klasę DictionaryBase i używa tej implementacji do utworzenia słownika String kluczy i wartości, które mają Length co najmniej 5 znaków.

C#
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

*/

Uwagi

Ważne

Nie zalecamy używania DictionaryBase klasy do nowego programowania. Zamiast tego zalecamy użycie klasy ogólnej Dictionary<TKey,TValue> lub KeyedCollection<TKey,TItem> klasy . Aby uzyskać więcej informacji, zobacz Kolekcje inne niż ogólne nie powinny być używane w usłudze GitHub.

Instrukcja foreach języka C# i instrukcja Visual Basic For Each zwracają obiekt typu elementów w kolekcji. Ponieważ każdy element DictionaryBase jest parą klucz/wartość, typ elementu nie jest typem klucza ani typem wartości. Zamiast tego typ elementu to DictionaryEntry.

Instrukcja foreach jest otoką wokół modułu wyliczającego, który umożliwia tylko odczytywanie, a nie zapisywanie w kolekcji.

Uwaga

Ponieważ klucze można dziedziczyć i zmieniać ich zachowanie, ich bezwzględna unikatowość nie może być gwarantowana przez porównania przy użyciu Equals metody .

Uwagi dotyczące implementowania

Ta klasa bazowa jest udostępniana, aby ułatwić implementatorom tworzenie silnie typizowanej kolekcji niestandardowej. Implementacje są zachęcane do rozszerzania tej klasy bazowej zamiast tworzenia własnych.

Elementy członkowskie tej klasy bazowej są chronione i mają być używane tylko za pośrednictwem klasy pochodnej.

Konstruktory

DictionaryBase()

Inicjuje nowe wystąpienie klasy DictionaryBase.

Właściwości

Count

Pobiera liczbę elementów zawartych w wystąpieniu DictionaryBase .

Dictionary

Pobiera listę elementów zawartych w wystąpieniu DictionaryBase .

InnerHashtable

Pobiera listę elementów zawartych w wystąpieniu DictionaryBase .

Metody

Clear()

Czyści zawartość DictionaryBase wystąpienia.

CopyTo(Array, Int32)

Kopiuje DictionaryBase elementy do jednowymiarowego Array w określonym indeksie.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
GetEnumerator()

Zwraca iterowanie IDictionaryEnumeratorDictionaryBase przez wystąpienie.

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera bieżące wystąpienie.

(Odziedziczone po Object)
MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
OnClear()

Wykonuje dodatkowe procesy niestandardowe przed wyczyszczeniem zawartości DictionaryBase wystąpienia.

OnClearComplete()

Wykonuje dodatkowe procesy niestandardowe po wyczyszczeniu zawartości DictionaryBase wystąpienia.

OnGet(Object, Object)

Pobiera element z określonym kluczem i wartością w wystąpieniu DictionaryBase .

OnInsert(Object, Object)

Wykonuje dodatkowe procesy niestandardowe przed wstawieniem nowego elementu do DictionaryBase wystąpienia.

OnInsertComplete(Object, Object)

Wykonuje dodatkowe procesy niestandardowe po wstawieniu nowego elementu do DictionaryBase wystąpienia.

OnRemove(Object, Object)

Wykonuje dodatkowe procesy niestandardowe przed usunięciem elementu z DictionaryBase wystąpienia.

OnRemoveComplete(Object, Object)

Wykonuje dodatkowe procesy niestandardowe po usunięciu DictionaryBase elementu z wystąpienia.

OnSet(Object, Object, Object)

Wykonuje dodatkowe procesy niestandardowe przed ustawieniem wartości w wystąpieniu DictionaryBase .

OnSetComplete(Object, Object, Object)

Wykonuje dodatkowe procesy niestandardowe po ustawieniu wartości w wystąpieniu DictionaryBase .

OnValidate(Object, Object)

Wykonuje dodatkowe procesy niestandardowe podczas sprawdzania poprawności elementu przy użyciu określonego klucza i wartości.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)

Jawne implementacje interfejsu

ICollection.IsSynchronized

Pobiera wartość wskazującą, czy dostęp do DictionaryBase obiektu jest synchronizowany (bezpieczny wątek).

ICollection.SyncRoot

Pobiera obiekt, który może służyć do synchronizowania dostępu do DictionaryBase obiektu.

IDictionary.Add(Object, Object)

Dodaje element z określonym kluczem i wartością do elementu DictionaryBase.

IDictionary.Contains(Object)

Określa, czy element DictionaryBase zawiera określony klucz.

IDictionary.IsFixedSize

Pobiera wartość wskazującą, czy DictionaryBase obiekt ma stały rozmiar.

IDictionary.IsReadOnly

Pobiera wartość wskazującą DictionaryBase , czy obiekt jest tylko do odczytu.

IDictionary.Item[Object]

Pobiera lub ustawia wartość skojarzona z określonym kluczem.

IDictionary.Keys

ICollection Pobiera obiekt zawierający klucze w DictionaryBase obiekcie.

IDictionary.Remove(Object)

Usuwa element z określonym kluczem z elementu DictionaryBase.

IDictionary.Values

ICollection Pobiera obiekt zawierający wartości w DictionaryBase obiekcie.

IEnumerable.GetEnumerator()

IEnumerator Zwraca iterowanie DictionaryBaseprzez element .

Metody rozszerzania

Cast<TResult>(IEnumerable)

Rzutuje elementy elementu IEnumerable do określonego typu.

OfType<TResult>(IEnumerable)

Filtruje elementy elementu IEnumerable na podstawie określonego typu.

AsParallel(IEnumerable)

Umożliwia równoległość zapytania.

AsQueryable(IEnumerable)

Konwertuje element IEnumerable na .IQueryable

Dotyczy

Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

Bezpieczeństwo wątkowe

Publiczne statyczne (Shared w Visual Basic) elementy członkowskie tego typu są bezpieczne wątkami. Wystąpienia elementów członkowskich nie dają gwarancji bezpieczeństwa wątków.

Ta implementacja nie zapewnia zsynchronizowanej (bezpiecznej wątkowo) otoki dla klasy pochodnej DictionaryBase, ale klasy pochodne mogą tworzyć własne zsynchronizowane wersje DictionaryBase właściwości SyncRoot .

Wyliczanie w kolekcji nie jest wewnętrznie procedurą odporną na wielowątkowość. Nawet gdy kolekcja jest synchronizowana, inne wątki nadal mogą ją modyfikować. Powoduje to zgłaszanie wyjątku przez moduł wyliczający. Aby zagwarantować bezpieczeństwo wątków podczas wyliczania, można zablokować kolekcję podczas całego procesu wyliczania albo rejestrować wyjątki wynikłe ze zmian wprowadzanych przez inne wątków.

Zobacz też