Język

Dictionary<TKey,TValue>.IDictionary.Item[Object] Właściwość

Definicja

Pobiera lub ustawia wartość za pomocą określonego klucza.

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

Parametry

key
Object

Klucz wartości do pobrania.

Wartość właściwości

Wartość skojarzona z określonym kluczem lub null jeśli key nie znajduje się w słowniku lub key jest typem, który nie można przypisać do typu TKey klucza .Dictionary<TKey,TValue>

Implementuje

Wyjątki

Parametr key ma wartość null.

Wartość jest przypisywana i key jest typu, który nie można przypisać do typu TKey klucza .Dictionary<TKey,TValue>

— lub —

Wartość jest przypisywana i jest typu, który nie można przypisać do typu TValue wartości .Dictionary<TKey,TValue>

Przykłady

W poniższym przykładzie kodu pokazano, jak używać IDictionary.Item[] właściwości (indeksatora w języku C#) interfejsu System.Collections.IDictionary z elementem Dictionary<TKey,TValue>, oraz sposobów, w jaki właściwość różni się od Dictionary<TKey,TValue>.Item[] właściwości .

W przykładzie Dictionary<TKey,TValue>.Item[] pokazano, że, podobnie jak właściwość, Dictionary<TKey,TValue>.IDictionary.Item[] właściwość może zmienić wartość skojarzona z istniejącym kluczem i może służyć do dodawania nowej pary klucz/wartość, jeśli określony klucz nie znajduje się w słowniku. W przykładzie pokazano również, Dictionary<TKey,TValue>.Item[] że w przeciwieństwie do Dictionary<TKey,TValue>.IDictionary.Item[] właściwości właściwość nie zgłasza wyjątku, jeśli key nie znajduje się w słowniku, zwraca zamiast tego odwołanie o wartości null. Na koniec przykład pokazuje, że pobieranie Dictionary<TKey,TValue>.IDictionary.Item[] właściwości zwraca odwołanie o wartości null, jeśli key nie jest poprawnym typem danych, a ustawienie właściwości zgłasza wyjątek, jeśli key nie jest poprawnym typem danych.

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");

        // The Item property is another name for the indexer, so you
        // can omit its name when accessing elements.
        Console.WriteLine($"""For key = "rtf", value = {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 = {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 = {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.");
        }

        // 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 = {openWith["tif"]}.""");
    }
}
open System
open System.Collections
open System.Collections.Generic

// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
let openWith: IDictionary = 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")

// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
printfn $"""For key = "rtf", value = {openWith.["rtf"]}."""

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] <- "winword.exe"
printfn $"""For key = "rtf", value = {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.
printfn "The indexer returns null if the key is of the wrong type:"
printfn $"""For key = 2, value = {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."
with :? ArgumentException ->
    printfn "A key of the wrong type was specified when assigning to the indexer."

// 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.
printfn $"""For key = "tif", value = {openWith.["tif"]}."""
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 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"))

    End Sub

End Class

Uwagi

Ta właściwość umożliwia dostęp do określonej wartości w kolekcji przy użyciu następującej składni języka C#: myCollection[key] (myCollection(key) w Visual Basic).

Możesz również użyć Item[] właściwości , aby dodać nowe elementy, ustawiając wartość klucza, który nie istnieje w słowniku, na przykład myCollection["myNonexistentKey"] = myValue. Jeśli jednak określony klucz już istnieje w słowniku, ustawienie Item[] właściwości zastępuje starą wartość. Add Natomiast metoda nie modyfikuje istniejących elementów.

Język C# używa tego słowa kluczowego do zdefiniowania indeksatorów zamiast implementowania IDictionary.Item[] właściwości. Język Visual Basic implementuje IDictionary.Item[] jako właściwość domyślną, która zapewnia tę samą funkcję indeksowania.

Pobieranie lub ustawianie wartości tej właściwości zbliża się do operacji O(1).

Dotyczy

Zobacz też