DictionaryEntry Структура

Определение

Определяет пару "ключ-значение словаря", которую можно задать или извлечь.

public value class DictionaryEntry
public struct DictionaryEntry
[System.Serializable]
public struct DictionaryEntry
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct DictionaryEntry
type DictionaryEntry = struct
[<System.Serializable>]
type DictionaryEntry = struct
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type DictionaryEntry = struct
Public Structure DictionaryEntry
Наследование
DictionaryEntry
Атрибуты

Примеры

В следующем примере показано использование DictionaryEntry итерации по объекту Hashtable .

// A simple example for the DictionaryEntry structure.
using System;
using System.Collections;

class Example
{
    public static void Main()
    {
        // Create a new hash table.
        //
        Hashtable openWith = new Hashtable();

        // Add some elements to the hash table. There are no
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

        // When you use foreach to enumerate hash table elements,
        // the elements are retrieved as DictionaryEntry objects.
        Console.WriteLine();
        foreach (DictionaryEntry de in openWith)
        {
            Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
        }
    }
}

/* This code example produces output similar to the following:

Key = rtf, Value = wordpad.exe
Key = txt, Value = notepad.exe
Key = dib, Value = paint.exe
Key = bmp, Value = paint.exe
 */
'A simple example for the DictionaryEntry structure.
Imports System.Collections

Module Example

    Sub Main()

        ' Create a new hash table.
        '
        Dim openWith As New Hashtable()

        ' Add some elements to the hash table. There are no
        ' duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")

        ' When you use For Each to enumerate hash table elements,
        ' the elements are retrieved as DictionaryEntry objects.
        Console.WriteLine()
        For Each de As DictionaryEntry In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                de.Key, de.Value)
        Next de

    End Sub

End Module

' This code example produces output similar to the following:
'
'Key = rtf, Value = wordpad.exe
'Key = txt, Value = notepad.exe
'Key = dib, Value = paint.exe
'Key = bmp, Value = paint.exe

Комментарии

Метод IDictionaryEnumerator.Entry возвращает экземпляр этого типа.

Это важно

Мы не рекомендуем использовать структуру DictionaryEntry для новой разработки. Вместо этого рекомендуется использовать универсальную KeyValuePair<TKey,TValue> структуру вместе с классом Dictionary<TKey,TValue> . Дополнительные сведения см. в статье, не относящийся к универсальным коллекциям, которые не должны использоваться на сайте GitHub.

Оператор C# foreach и оператор Visual Basic For Each требует типа каждого элемента в коллекции. Так как каждый элемент является парой "ключ-значение", тип элемента IDictionary не является типом ключа или типа значения. Вместо этого тип элемента имеет тип DictionaryEntry. Рассмотрим пример.

foreach (DictionaryEntry de in openWith)
{
    Console.WriteLine("Key = {0}, Value = {1}", de.Key, de.Value);
}
For Each de As DictionaryEntry In openWith
    Console.WriteLine("Key = {0}, Value = {1}", _
        de.Key, de.Value)
Next de

Оператор foreach представляет собой оболочку вокруг перечислителя, которая позволяет только читать из коллекции, а не записывать в нее.

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

Имя Описание
DictionaryEntry(Object, Object)

Инициализирует экземпляр DictionaryEntry типа с указанным ключом и значением.

Свойства

Имя Описание
Key

Возвращает или задает ключ в паре "ключ-значение".

Value

Возвращает или задает значение в паре "ключ-значение".

Методы

Имя Описание
Deconstruct(Object, Object)

Деконструкция текущего DictionaryEntry.

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

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