Прочитать на английском

Поделиться через


StringDictionary Класс

Определение

Реализует хэш-таблицу с ключом и значением, строго типизированными как строки, а не объекты.

public class StringDictionary : System.Collections.IEnumerable
[System.Serializable]
public class StringDictionary : System.Collections.IEnumerable
Наследование
StringDictionary
Атрибуты
Реализации

Примеры

В следующем примере кода демонстрируется несколько свойств и методов .StringDictionary

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

public class SamplesStringDictionary  {

   public static void Main()  {

      // Creates and initializes a new StringDictionary.
      StringDictionary myCol = new StringDictionary();
      myCol.Add( "red", "rojo" );
      myCol.Add( "green", "verde" );
      myCol.Add( "blue", "azul" );

      // Display the contents of the collection using foreach. This is the preferred method.
      Console.WriteLine( "Displays the elements using foreach:" );
      PrintKeysAndValues1( myCol );

      // Display the contents of the collection using the enumerator.
      Console.WriteLine( "Displays the elements using the IEnumerator:" );
      PrintKeysAndValues2( myCol );

      // Display the contents of the collection using the Keys, Values, Count, and Item properties.
      Console.WriteLine( "Displays the elements using the Keys, Values, Count, and Item properties:" );
      PrintKeysAndValues3( myCol );

      // Copies the StringDictionary to an array with DictionaryEntry elements.
      DictionaryEntry[] myArr = new DictionaryEntry[myCol.Count];
      myCol.CopyTo( myArr, 0 );

      // Displays the values in the array.
      Console.WriteLine( "Displays the elements in the array:" );
      Console.WriteLine( "   KEY        VALUE" );
      for ( int i = 0; i < myArr.Length; i++ )
         Console.WriteLine( "   {0,-10} {1}", myArr[i].Key, myArr[i].Value );
      Console.WriteLine();

      // Searches for a value.
      if ( myCol.ContainsValue( "amarillo" ) )
         Console.WriteLine( "The collection contains the value \"amarillo\"." );
      else
         Console.WriteLine( "The collection does not contain the value \"amarillo\"." );
      Console.WriteLine();

      // Searches for a key and deletes it.
      if ( myCol.ContainsKey( "green" ) )
         myCol.Remove( "green" );
      Console.WriteLine( "The collection contains the following elements after removing \"green\":" );
      PrintKeysAndValues1( myCol );

      // Clears the entire collection.
      myCol.Clear();
      Console.WriteLine( "The collection contains the following elements after it is cleared:" );
      PrintKeysAndValues1( myCol );
   }

   // 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( StringDictionary myCol )  {
      Console.WriteLine( "   KEY                       VALUE" );
      foreach ( DictionaryEntry de in myCol )
         Console.WriteLine( "   {0,-25} {1}", de.Key, de.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( StringDictionary myCol )  {
      IEnumerator myEnumerator = myCol.GetEnumerator();
      DictionaryEntry de;
      Console.WriteLine( "   KEY                       VALUE" );
      while ( myEnumerator.MoveNext() )  {
         de = (DictionaryEntry) myEnumerator.Current;
         Console.WriteLine( "   {0,-25} {1}", de.Key, de.Value );
      }
      Console.WriteLine();
   }

   // Uses the Keys, Values, Count, and Item properties.
   public static void PrintKeysAndValues3( StringDictionary myCol )  {
      String[] myKeys = new String[myCol.Count];
      myCol.Keys.CopyTo( myKeys, 0 );

      Console.WriteLine( "   INDEX KEY                       VALUE" );
      for ( int i = 0; i < myCol.Count; i++ )
         Console.WriteLine( "   {0,-5} {1,-25} {2}", i, myKeys[i], myCol[myKeys[i]] );
      Console.WriteLine();
   }
}

/*
This code produces the following output.

Displays the elements using foreach:
   KEY                       VALUE
   red                       rojo
   blue                      azul
   green                     verde

Displays the elements using the IEnumerator:
   KEY                       VALUE
   red                       rojo
   blue                      azul
   green                     verde

Displays the elements using the Keys, Values, Count, and Item properties:
   INDEX KEY                       VALUE
   0     red                       rojo
   1     blue                      azul
   2     green                     verde

Displays the elements in the array:
   KEY        VALUE
   red        rojo
   blue       azul
   green      verde

The collection does not contain the value "amarillo".

The collection contains the following elements after removing "green":
   KEY                       VALUE
   red                       rojo
   blue                      azul

The collection contains the following elements after it is cleared:
   KEY                       VALUE

*/

Комментарии

Ключ не может быть null, но значение может.

Ключ обрабатывается без учета регистра; перед использованием со строковым словарем он преобразуется в нижний регистр.

В платформа .NET Framework версии 1.0 этот класс использует сравнение строк с учетом языка и региональных параметров. Однако в платформа .NET Framework версии 1.1 и более поздних этот класс использует CultureInfo.InvariantCulture при сравнении строк. Дополнительные сведения о том, как язык и региональные параметры влияют на сравнение и сортировку, см. в разделе Выполнение Culture-Insensitive строковых операций.

Конструкторы

StringDictionary()

Инициализирует новый экземпляр класса StringDictionary.

Свойства

Count

Получает число пар ключ/значение, содержащихся в StringDictionary.

IsSynchronized

Возвращает значение, показывающее, является ли доступ к коллекции StringDictionary синхронизированным (потокобезопасным).

Item[String]

Возвращает или задает значение, связанное с указанным ключом.

Keys

Получает коллекцию ключей в StringDictionary.

SyncRoot

Получает объект, с помощью которого можно синхронизировать доступ к коллекции StringDictionary.

Values

Получает коллекцию значений в StringDictionary.

Методы

Add(String, String)

Добавляет запись с указанными ключом и значением в StringDictionary.

Clear()

Удаляет все записи из StringDictionary.

ContainsKey(String)

Определяет, содержит ли StringDictionary указанный ключ.

ContainsValue(String)

Определяет, содержит ли StringDictionary указанное значение.

CopyTo(Array, Int32)

Копирует значения из словаря строк в одномерный экземпляр класса Array по указанному индексу.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetEnumerator()

Возвращает перечислитель, который осуществляет перебор элементов словаря строк.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает объект Type для текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неполную копию текущего объекта Object.

(Унаследовано от Object)
Remove(String)

Удаляет запись с указанным ключом из словаря строк.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Методы расширения

Cast<TResult>(IEnumerable)

Приводит элементы объекта IEnumerable к заданному типу.

OfType<TResult>(IEnumerable)

Выполняет фильтрацию элементов объекта IEnumerable по заданному типу.

AsParallel(IEnumerable)

Позволяет осуществлять параллельный запрос.

AsQueryable(IEnumerable)

Преобразовывает коллекцию IEnumerable в объект IQueryable.

Применяется к

Продукт Версии
.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

Потокобезопасность

Открытые статические (Shared в Visual Basic) члены этого типа являются потокобезопасными. Потокобезопасная работа с членами экземпляров типа не гарантируется.

Эта реализация не предоставляет синхронизированную (потокобезопасную) оболочку StringDictionaryдля , но производные классы могут создавать собственные синхронизированные StringDictionary версии с помощью SyncRoot свойства .

Перечисление коллекции не является потокобезопасной процедурой. Даже если коллекция синхронизирована, другие потоки могут ее изменить, что приведет к тому, что перечислитель создаст исключение. Для обеспечения потокобезопасности при перечислении можно либо заблокировать коллекцию на все время перечисления, либо перехватывать исключения, возникающие в результате изменений, внесенных другими потоками.

См. также раздел