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

정의

지정된 키를 가진 값을 가져오거나 설정합니다.

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

매개 변수

key
Object

가져올 값의 키입니다.

속성 값

지정된 키와 연결된 값이거나 null 사전에 key 없거나 키 형식에 할당할 수 없는 형식 Dictionary<TKey,TValue>TKey 인 경우 key 입니다.

구현

예외

keynull입니다.

값이 할당되고 있으며 key 키 형식에 할당할 수 없는 형식 TKeyDictionary<TKey,TValue>입니다.

-또는-

값이 할당되고 있으며 값 형식에 할당할 수 없는 형식 TValue 입니다 Dictionary<TKey,TValue>.

예제

다음 코드 예제에서는 인터페이스의 IDictionary.Item[] 속성(C#의 System.Collections.IDictionary 인덱서)을 사용하는 Dictionary<TKey,TValue>방법과 속성이 속성과 다른 방법을 보여 줍니다 Dictionary<TKey,TValue>.Item[] .

이 예제에서는 속성 Dictionary<TKey,TValue>.IDictionary.Item[] 과 마찬가지로 Dictionary<TKey,TValue>.Item[] 속성이 기존 키와 연결된 값을 변경할 수 있으며 지정된 키가 사전에 없는 경우 새 키/값 쌍을 추가하는 데 사용할 수 있음을 보여줍니다. 또한 이 예제에서는 속성 Dictionary<TKey,TValue>.IDictionary.Item[]Dictionary<TKey,TValue>.Item[] 달리 사전에 없는 경우 key 속성이 예외를 throw하지 않고 null 참조를 대신 반환하는 것을 보여 있습니다. 마지막으로, 이 예제에서는 속성이 올바른 데이터 형식이 Dictionary<TKey,TValue>.IDictionary.Item[] 아닌 경우 key null 참조를 반환하고 속성 설정이 올바른 데이터 형식이 아닌 경우 key 예외를 throw하는 것을 보여 줍니다.

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

설명

이 속성은 다음 C# 구문을 사용하여 컬렉션의 특정 값에 액세스할 수 있는 기능을 제공합니다. myCollection[key](Visual Basic myCollection(key)).

사전에 존재하지 않는 키의 값을 설정하여 새 요소를 추가할 수도 Item[] 있습니다. 예를 들면 myCollection["myNonexistentKey"] = myValue다음과 같습니다. 그러나 지정된 키가 사전에 이미 있는 경우 속성을 설정 Item[] 하면 이전 값이 덮어씁니다. 반면, 메서드는 Add 기존 요소를 수정하지 않습니다.

C# 언어는 키워드를 사용하여 속성을 구현하는 대신 인덱서를 정의합니다 IDictionary.Item[] . Visual Basic은 IDictionary.Item[] 동일한 인덱싱 기능을 제공하는 기본 속성으로 구현합니다.

이 속성의 값을 가져오거나 설정하면 O(1) 작업에 접근합니다.

적용 대상

추가 정보