Dictionary<TKey,TValue>.Item[TKey] Eigenschap

Definitie

Hiermee haalt u de waarde op die is gekoppeld aan de opgegeven sleutel of stelt u deze in.

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

Parameters

key
TKey

De sleutel van de waarde die moet worden opgehaald of ingesteld.

Waarde van eigenschap

TValue

De waarde die is gekoppeld aan de opgegeven sleutel. Als de opgegeven sleutel niet wordt gevonden, genereert een get-bewerking een KeyNotFoundExceptionen een setbewerking maakt een nieuw element met de opgegeven sleutel.

Implementeringen

Uitzonderingen

key is null.

De eigenschap wordt opgehaald en key bestaat niet in de verzameling.

Voorbeelden

In het volgende codevoorbeeld wordt de Item[] eigenschap (de indexeerfunctie in C#) gebruikt om waarden op te halen, om aan te tonen dat er een KeyNotFoundException wordt gegenereerd wanneer een aangevraagde sleutel niet aanwezig is en dat de waarde die is gekoppeld aan een sleutel kan worden vervangen.

In het voorbeeld ziet u ook hoe u de TryGetValue methode gebruikt als een efficiëntere manier om waarden op te halen als een programma vaak sleutelwaarden moet proberen die zich niet in de woordenlijst bevinden.

Dit codevoorbeeld maakt deel uit van een groter voorbeeld voor de Dictionary<TKey,TValue> klasse. openWith is de naam van de woordenlijst die in dit voorbeeld wordt gebruikt.

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

Opmerkingen

Deze eigenschap biedt de mogelijkheid om toegang te krijgen tot een specifiek element in de verzameling met behulp van de volgende C#-syntaxis: myCollection[key] (myCollection(key) in Visual Basic).

U kunt de Item[] eigenschap ook gebruiken om nieuwe elementen toe te voegen door de waarde in te stellen van een sleutel die niet bestaat in de Dictionary<TKey,TValue>. Wanneer u de eigenschapswaarde instelt en de sleutel zich in de Dictionary<TKey,TValue>sleutel bevindt, wordt de waarde die aan die sleutel is gekoppeld, vervangen door de toegewezen waarde. Als de sleutel zich niet in de Dictionary<TKey,TValue>sleutel bevindt, worden de sleutel en waarde toegevoegd aan de woordenlijst. De methode wijzigt daarentegen Add geen bestaande elementen.

Een sleutel kan niet zijn null, maar een waarde kan zijn, als het waardetype een verwijzingstype TValue is.

De C#-taal gebruikt het this trefwoord om de indexeerfuncties te definiëren in plaats van de Item[] eigenschap te implementeren. Visual Basic implementeert Item[] als een standaardeigenschap, die dezelfde indexeringsfunctionaliteit biedt.

Het ophalen of instellen van de waarde van deze eigenschap benadert een O(1)-bewerking.

Van toepassing op

Zie ook