SortedList<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, którego wartość ma zostać pobrana lub ustawiona.

Wartość właściwości

TValue

Wartość skojarzona z określonym kluczem. Jeśli określony klucz nie zostanie znaleziony, operacja get zgłasza operację KeyNotFoundException i zestaw tworzy nowy element przy użyciu określonego klucza.

Implementuje

Wyjątki

key to 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 (indeksatora w języku C#) do pobierania wartości, co pokazuje, że element KeyNotFoundException jest zgłaszany, gdy żądany klucz nie jest obecny, i pokazuje, że wartość skojarzona z kluczem może zostać zamieniona.

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ę na posortowanej liście.

Ten przykład kodu jest częścią większego przykładu podanego SortedList<TKey,TValue> dla klasy.

// 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 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 throws an exception if the requested key is
// not in the list.
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 list.
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 list.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// The indexer throws an exception if the requested key is
// not in the list.
try
    printfn $"""For key = "tif", value = {openWith["tif"]}."""
with 
    | :? KeyNotFoundException ->
        printfn "Key = \"tif\" is not found."
// When a program often has to try keys that turn out not to
// be in the list, 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 list, 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 list, 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
// When a program often has to try keys that turn out not to
// be in the list, TryGetValue can be a more efficient
// way to retrieve values.
match openWith.TryGetValue("tif") with
| true, value ->
    printfn "For key = \"tif\", value = {value}."
| false, _ ->
    printfn "Key = \"tif\" is not found."

Uwagi

Ta właściwość umożliwia dostęp do określonego elementu w kolekcji przy użyciu następującej składni: myCollection[key].

Kluczem nie może być null, ale wartość może być, jeśli typ wartości na liście, TValuejest typem odwołania.

Jeśli klucz nie zostanie znaleziony po pobraniu wartości, KeyNotFoundException zostanie zgłoszony. Jeśli klucz nie zostanie znaleziony po ustawieniu wartości, klucz i wartość zostaną dodane.

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

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

Pobieranie wartości tej właściwości jest operacją O(log n), gdzie n to Count. Ustawienie właściwości to operacja O(log n), jeśli klucz znajduje się już w obiekcie SortedList<TKey,TValue>. Jeśli klucz nie znajduje się na liście, ustawienie właściwości jest operacją O(n) dla nieortowanych danych lub O(log n), jeśli nowy element zostanie dodany na końcu listy. Jeśli wstawienie powoduje zmianę rozmiaru, operacja to O(n).

Dotyczy

Zobacz też