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

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


StringDictionary.Item[String] Свойство

Определение

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

public virtual string this[string key] { get; set; }
public virtual string? this[string key] { get; set; }

Параметры

key
String

Задаваемое или получаемое значение ключа.

Значение свойства

Значение, связанное с указанным ключом. Если указанный ключ не найден, оператор Get возвращает значение null, а оператор Set создает новую запись с указанным ключом.

Исключения

key имеет значение null.

Примеры

В следующем примере кода перечисляются элементы 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 );
   }

   // 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

*/

Комментарии

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

Ключ не может быть null, но значение может. Чтобы различать null возвращаемый ключ, так как указанный ключ не найден, и null возвращаемый из-за того, что значение указанного ключа равно null, используйте ContainsKey метод , чтобы определить, существует ли ключ в списке.

Язык C# использует этот ключевое слово для определения индексаторов вместо реализации Item[] свойства . В языке Visual Basic в качестве свойства по умолчанию реализовано свойство Item[], предоставляющее те же возможности индексирования.

Получение значения этого свойства является операцией O(1); Установка свойства также является операцией O(1).

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

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

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