Język

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

Definicja

Pobiera lub ustawia wartość skojarzona z określonym kluczem.

public:
 property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); };
public TValue this[TKey key] { get; set; }
member this.Item('Key) : 'Value with get, set
Default Public Property Item(key As TKey) As TValue

Parametry

key
TKey

Klucz wartości do pobrania lub ustawienia.

Wartość właściwości

TValue

Wartość skojarzona z określonym kluczem. Jeśli określony klucz nie zostanie znaleziony KeyNotFoundException, operacja get zgłasza element , a operacja zestawu tworzy nowy element z określonym kluczem.

Implementuje

Wyjątki

Parametr key ma wartość null.

Właściwość jest pobierana i key nie istnieje w kolekcji.

Przykłady

Poniższy przykład kodu używa Item[] właściwości (indeksator w języku C#) do pobierania wartości, pokazując, że element jest zgłaszany, gdy żądany klucz nie jest obecny, i pokazuje, że KeyNotFoundException można zamienić wartość skojarzona z kluczem.

W przykładzie pokazano również, jak używać TryGetValue metody jako bardziej wydajnego sposobu pobierania wartości, jeśli program często musi wypróbować wartości kluczy, które nie znajdują się w słowniku.

Ten przykład kodu jest częścią większego przykładu udostępnionego dla klasy Dictionary<TKey,TValue>. openWith to nazwa słownika używanego w tym przykładzie.

// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
    new Dictionary<string, string>();

// Add some elements to the dictionary. 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");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// Create a new dictionary of strings, with string keys.
let openWith = Dictionary<string, string>()

// Add some elements to the dictionary. 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")

// The Add method throws an exception if the new key is
// already in the dictionary.
try
    openWith.Add("txt", "winword.exe")
with :? ArgumentException ->
    printfn "An element with Key = \"txt\" already exists."
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of String, String)

' Add some elements to the dictionary. 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")

' The Add method throws an exception if the new key is 
' already in the dictionary.
Try
    openWith.Add("txt", "winword.exe")
Catch 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// 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 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 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 indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
    printfn $"""For key = "tif", value = {openWith["tif"]}"""
with :? KeyNotFoundException ->
    printfn "Key = \"tif\" is not found."
' The default Item property throws an exception if the requested
' key is not in the dictionary.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue "tif" with
| true, value -> printfn $"For key = \"tif\", value = {value}."
| _ -> printfn "Key = \"tif\" is not found."
' When a program often has to try keys that turn out not to
' be in the dictionary, TryGetValue can be a more efficient 
' way to retrieve values.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
    Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
    Console.WriteLine("Key = ""tif"" is not found.")
End If

Uwagi

Ta właściwość umożliwia dostęp do określonego elementu 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 obiekcie Dictionary<TKey,TValue>. Po ustawieniu wartości właściwości, jeśli klucz znajduje się w Dictionary<TKey,TValue>obiekcie , wartość skojarzona z tym kluczem jest zastępowana przez przypisaną wartość. Jeśli klucz nie znajduje się w Dictionary<TKey,TValue>obiekcie , klucz i wartość zostaną dodane do słownika. Add Natomiast metoda nie modyfikuje istniejących elementów.

Kluczem nie może być null, ale może to być wartość, jeśli typ wartości jest typem TValue odwołania.

Język C# używa słowa kluczowego this do zdefiniowania indeksatorów zamiast implementowania Item[] właściwości. Język Visual Basic implementuje 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ż