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

Ключ элемента, который требуется получить.

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

Object

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

Реализации

Исключения

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

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

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

Примеры

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

В примере показано, что, как SortedDictionary<TKey,TValue>.Item[] и свойство, свойство может изменить значение, связанное с существующим ключом, и может использоваться для добавления новой пары "ключ-значение", SortedDictionary<TKey,TValue>.IDictionary.Item[] если указанный ключ отсутствует в словаре. В примере также показано, что в отличие от SortedDictionary<TKey,TValue>.Item[] свойства, свойство не создает исключение, SortedDictionary<TKey,TValue>.IDictionary.Item[] если key оно отсутствует в словаре, возвращая вместо этого пустую ссылку. Наконец, в примере показано, что получение SortedDictionary<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 sorted dictionary of strings, with string keys,
        // and access it using the IDictionary interface.
        //
        IDictionary openWith = new SortedDictionary<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 sorted dictionary of strings, with string keys,
        ' and access it using the IDictionary interface.
        '
        Dim openWith As IDictionary = _
            New SortedDictionary(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[] свойства перезаписывает старое значение. Напротив, IDictionary.Add метод не изменяет существующие элементы.

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

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

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

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