Dictionary<TKey,TValue>.IDictionary.Item[Object] Свойство

Определение

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

property System::Object ^ System::Collections::IDictionary::Item[System::Object ^] { System::Object ^ get(System::Object ^ key); void set(System::Object ^ key, System::Object ^ value); };
object System.Collections.IDictionary.Item[object key] { get; set; }
object? System.Collections.IDictionary.Item[object key] { get; set; }
member this.System.Collections.IDictionary.Item(obj) : obj with get, set
 Property Item(key As Object) As Object Implements IDictionary.Item

Параметры

key
Object

Ключ значения, которое необходимо получить.

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

Значение, связанное с указанным ключом, или null, если key отсутствует в словаре или key имеет тип, который не допускает присваивание типу ключа TKey коллекции Dictionary<TKey,TValue>.

Реализации

Исключения

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

Назначаемое значение и параметр key типа, который не может быть назначен типу ключа TKey объекта Dictionary<TKey,TValue>.

-или-

Значение присваивается, при этом тип параметра value не допускает присваивание типу значения TValue объекту Dictionary<TKey,TValue>.

Примеры

В следующем примере кода показано, как использовать IDictionary.Item[] свойство (индексатор в C#) System.Collections.IDictionary интерфейса с Dictionary<TKey,TValue>и чем свойство отличается от Dictionary<TKey,TValue>.Item[] свойства .

В примере показано, что, как и Dictionary<TKey,TValue>.Item[] свойство, свойство может изменять значение, Dictionary<TKey,TValue>.IDictionary.Item[] связанное с существующим ключом, и может использоваться для добавления новой пары "ключ-значение", если указанный ключ отсутствует в словаре. В примере также показано, что, в Dictionary<TKey,TValue>.Item[] отличие от свойства, Dictionary<TKey,TValue>.IDictionary.Item[] свойство не создает исключение, если key его нет в словаре, возвращая вместо этого пустую ссылку. Наконец, в примере показано, что получение Dictionary<TKey,TValue>.IDictionary.Item[] свойства возвращает пустую ссылку, если key не является правильным типом данных, и что задание свойства вызывает исключение, если key не является правильным типом данных.

Пример кода является частью более крупного примера, включая выходные данные, предоставленные IDictionary.Add для метода .

using System;
using System.Collections;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        // Create a new dictionary of strings, with string keys,
        // and access it using the IDictionary interface.
        //
        IDictionary openWith = new Dictionary<string, string>();

        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        // IDictionary.Add throws an exception if incorrect types
        // are supplied for key or value.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");
Imports System.Collections
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new dictionary of strings, with string keys,
        ' and access it using the IDictionary interface.
        '
        Dim openWith As IDictionary = _
            New Dictionary(Of String, String)
        
        ' Add some elements to the dictionary. There are no 
        ' duplicate keys, but some of the values are duplicates.
        ' IDictionary.Add throws an exception if incorrect types
        ' are supplied for key or value.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";

// The indexer returns null if the key is of the wrong data
// type.
Console.WriteLine("The indexer returns null"
    + " if the key is of the wrong type:");
Console.WriteLine("For key = 2, value = {0}.",
    openWith[2]);

// The indexer throws an exception when setting a value
// if the key is of the wrong data type.
try
{
    openWith[2] = "This does not get added.";
}
catch (ArgumentException)
{
    Console.WriteLine("A key of the wrong type was specified"
        + " when assigning to the indexer.");
}
' The Item property is the default property, so you 
' can omit its name when accessing elements. 
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' The default Item property can be used to change the value
' associated with a key.
openWith("rtf") = "winword.exe"
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' If a key does not exist, setting the default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"

' The default Item property returns Nothing if the key
' is of the wrong data type.
Console.WriteLine("The default Item property returns Nothing" _
    & " if the key is of the wrong type:")
Console.WriteLine("For key = 2, value = {0}.", _
    openWith(2))

' The default Item property throws an exception when setting
' a value if the key is of the wrong data type.
Try
    openWith(2) = "This does not get added."
Catch 
    Console.WriteLine("A key of the wrong type was specified" _
        & " when setting the default Item property.")
End Try
// Unlike the default Item property on the Dictionary class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the dictionary.
Console.WriteLine("For key = \"tif\", value = {0}.",
    openWith["tif"]);
' Unlike the default Item property on the Dictionary class
' itself, IDictionary.Item does not throw an exception
' if the requested key is not in the dictionary.
Console.WriteLine("For key = ""tif"", value = {0}.", _
    openWith("tif"))
    }
}

    End Sub

End Class

Комментарии

Это свойство предоставляет возможность доступа к определенному значению в коллекции с помощью следующего синтаксиса C#: myCollection[key] (myCollection(key) в Visual Basic).

Свойство также можно использовать для Item[] добавления новых элементов, задав значение ключа, не существующего в словаре, например myCollection["myNonexistentKey"] = myValue. Однако если указанный ключ уже существует в словаре, установка Item[] свойства перезаписывает старое значение. В отличие от этого, Add метод не изменяет существующие элементы.

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

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

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

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