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

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

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

Элемент с указанным ключом или nullkey не входит в словарь или key имеет тип, который не может назначаться типу TKeySortedDictionary<TKey,TValue>ключа.

Реализации

Исключения

key равно null.

Присваивается значение и key является типом, который не может назначаться типу ключаTKey.SortedDictionary<TKey,TValue>

–или–

Присваивается значение и является типом, который не может присваиваться типу 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).

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

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