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

Definition

Ruft den Wert ab, der dem angegebenen Schlüssel zugeordnet ist, oder legt diesen fest.

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

Parameter

key
TKey

Der Schlüssel des abzurufenden oder festzulegenden Werts.

Eigenschaftswert

TValue

Der dem angegebenen Schlüssel zugeordnete Wert. Wenn der angegebene Schlüssel nicht gefunden wird, löst ein Get-Vorgang eine KeyNotFoundException aus, und durch einen Set-Vorgang wird ein neues Element mit dem angegebenen Schlüssel erstellt.

Implementiert

Ausnahmen

key ist null.

Die Eigenschaft wird abgerufen, und key ist in der Sammlung nicht vorhanden.

Beispiele

Im folgenden Codebeispiel wird die Item[] Eigenschaft (der Indexer in C#) verwendet, um Werte abzurufen, die demonstrieren, dass ein KeyNotFoundException Angeforderter Schlüssel nicht vorhanden ist und zeigt, dass der wert, der einem Schlüssel zugeordnet ist, ersetzt werden kann.

Das Beispiel zeigt auch, wie Sie die TryGetValue Methode als effizientere Methode zum Abrufen von Werten verwenden, wenn ein Programm häufig wichtige Werte ausprobieren muss, die nicht im Wörterbuch enthalten sind.

Dieses Codebeispiel ist Teil eines größeren Beispiels, das für die Dictionary<TKey,TValue> Klasse bereitgestellt wird. openWith ist der Name des Wörterbuchs, das in diesem Beispiel verwendet wird.

// Create a new dictionary of strings, with string keys.
//
Dictionary<String^, String^>^ openWith =
    gcnew 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.
//
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.
'
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.
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 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
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("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", 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.
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.
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

Hinweise

Diese Eigenschaft bietet die Möglichkeit, mithilfe der folgenden C#-Syntax auf ein bestimmtes Element in der Auflistung zuzugreifen: myCollection[key] (myCollection(key) in Visual Basic).

Sie können die Item[] Eigenschaft auch verwenden, um neue Elemente hinzuzufügen, indem Sie den Wert eines Schlüssels festlegen, der nicht in der Dictionary<TKey,TValue>. Wenn Sie den Eigenschaftswert festlegen, wird der Dictionary<TKey,TValue>dem Schlüssel zugeordnete Wert durch den zugewiesenen Wert ersetzt. Wenn sich der Schlüssel nicht im Dictionary<TKey,TValue>Verzeichnis befindet, werden der Schlüssel und der Wert dem Wörterbuch hinzugefügt. Im Gegensatz dazu ändert die Add Methode keine vorhandenen Elemente.

Ein Schlüssel kann nicht sein null, aber ein Wert kann sein, wenn der Werttyp ein Bezugstyp TValue ist.

Die C#-Sprache verwendet das this Schlüsselwort, um die Indexer zu definieren, anstatt die Item[] Eigenschaft zu implementieren. Visual Basic implementiert Item[] als Standardeigenschaft und stellt auf diese Weise dieselbe Indizierungsfunktionalität bereit.

Abrufen oder Festlegen des Werts dieser Eigenschaft nähert sich einem O(1)-Vorgang.

Gilt für:

Siehe auch