Dictionary<TKey,TValue>.IDictionary.Item[Object] Egenskap

Definition

Hämtar eller anger värdet med den angivna nyckeln.

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; }
member this.System.Collections.IDictionary.Item(obj) : obj with get, set
 Property Item(key As Object) As Object Implements IDictionary.Item

Parametrar

key
Object

Nyckeln för det värde som ska hämtas.

Egenskapsvärde

Värdet som är associerat med den angivna nyckeln, eller null om key det inte finns i ordlistan eller key är av en typ som inte kan tilldelas till nyckeltypen TKeyDictionary<TKey,TValue>för .

Implementeringar

Undantag

key är null.

Ett värde tilldelas och key är av en typ som inte kan tilldelas till nyckeltypen TKey för Dictionary<TKey,TValue>.

-eller-

Ett värde tilldelas och är av en typ som inte kan tilldelas till värdetypen TValue för Dictionary<TKey,TValue>.

Exempel

Följande kodexempel visar hur du använder IDictionary.Item[] egenskapen (indexeraren i C#) System.Collections.IDictionary i gränssnittet med en Dictionary<TKey,TValue>, och hur egenskapen skiljer sig från Dictionary<TKey,TValue>.Item[] egenskapen.

Exemplet visar att egenskapen, precis som Dictionary<TKey,TValue>.Item[] egenskapen, Dictionary<TKey,TValue>.IDictionary.Item[] kan ändra värdet som är associerat med en befintlig nyckel och kan användas för att lägga till ett nytt nyckel/värde-par om den angivna nyckeln inte finns i ordlistan. Exemplet visar också att egenskapen till Dictionary<TKey,TValue>.IDictionary.Item[] skillnad från Dictionary<TKey,TValue>.Item[] egenskapen inte utlöser ett undantag om key den inte finns i ordlistan och returnerar en null-referens i stället. Slutligen visar exemplet att hämtar Dictionary<TKey,TValue>.IDictionary.Item[] egenskapen returnerar en null-referens om key den inte är rätt datatyp, och att inställningen av egenskapen utlöser ett undantag om key det inte är rätt datatyp.

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

Kommentarer

Den här egenskapen ger möjlighet att komma åt ett specifikt värde i samlingen med hjälp av följande C#-syntax: myCollection[key] (myCollection(key) i Visual Basic).

Du kan också använda Item[] egenskapen för att lägga till nya element genom att ange värdet för en nyckel som inte finns i ordlistan, myCollection["myNonexistentKey"] = myValuetill exempel . Men om den angivna nyckeln redan finns i ordlistan skriver egenskapen Item[] över det gamla värdet. Metoden ändrar däremot Add inte befintliga element.

C#-språket använder det här nyckelordet för att definiera indexerarna i stället för att IDictionary.Item[] implementera egenskapen. Visual Basic implementerar IDictionary.Item[] som en standardegenskap, vilket ger samma indexeringsfunktioner.

När du hämtar eller anger värdet för den här egenskapen används en O(1)-åtgärd.

Gäller för

Se även