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

정의

지정된 키와 연결된 값을 가져오거나 설정합니다.Gets or sets the value associated with the specified key.

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

매개 변수

key
TKey

가져오거나 설정할 값의 키입니다.The key of the value to get or set.

속성 값

TValue

지정된 키와 연관된 값입니다.The value associated with the specified key. 지정한 키가 없으면 get 작업에서 KeyNotFoundException을 throw하고 set 작업에서 지정한 키가 있는 새 요소를 만듭니다.If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

구현

예외

key 에 선언된 기본값은 null입니다.key is null.

속성을 검색할 때 컬렉션에 key가 없는 경우The property is retrieved and key does not exist in the collection.

예제

다음 코드 예제에서는 Item[TKey] 속성 (의 C#인덱서)을 사용 하 여 값을 검색 하 고, 요청 된 키가 없을 때 KeyNotFoundException throw 되 고, 키와 연결 된 값을 바꿀 수 있음을 보여 줍니다.The following code example uses the Item[TKey] property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

또한이 예제에서는 프로그램에서 사전에 없는 키 값을 시도해 야 하는 경우 값을 검색 하는 보다 효율적인 방법으로 TryGetValue 메서드를 사용 하는 방법을 보여 줍니다.The example also shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary.

이 코드 예제는에 대해 제공 된 큰 예제의 일부는 Dictionary<TKey,TValue> 클래스입니다.This code example is part of a larger example provided for the Dictionary<TKey,TValue> class. openWith은이 예제에 사용 된 사전의 이름입니다.openWith is the name of the Dictionary used in this example.

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

설명

이 속성은 다음 C# 구문을 사용 하 여 컬렉션의 특정 요소에 액세스할 수 있는 기능을 제공 합니다. myCollection[key] (myCollection(key) Visual Basic).This property provides the ability to access a specific element in the collection by using the following C# syntax: myCollection[key] (myCollection(key) in Visual Basic).

Item[TKey] 속성을 사용 하 여 Dictionary<TKey,TValue>에 없는 키 값을 설정 하 여 새 요소를 추가할 수도 있습니다.You can also use the Item[TKey] property to add new elements by setting the value of a key that does not exist in the Dictionary<TKey,TValue>. 속성 값을 설정 하는 경우 키가 Dictionary<TKey,TValue>에 있으면 해당 키와 연결 된 값이 할당 된 값으로 바뀝니다.When you set the property value, if the key is in the Dictionary<TKey,TValue>, the value associated with that key is replaced by the assigned value. 키가 Dictionary<TKey,TValue>에 없는 경우 키와 값이 사전에 추가 됩니다.If the key is not in the Dictionary<TKey,TValue>, the key and value are added to the dictionary. 반면 Add 메서드는 기존 요소를 수정 하지 않습니다.In contrast, the Add method does not modify existing elements.

키를 null수는 없지만 값 형식이 TValue 참조 형식인 경우 값은 일 수 있습니다.A key cannot be null, but a value can be, if the value type TValue is a reference type.

이 C# 언어는 Item[TKey] 속성을 구현 하는 대신 this 키워드를 사용 하 여 인덱서를 정의 합니다.The C# language uses the this keyword to define the indexers instead of implementing the Item[TKey] property. Visual Basic에서는 동일한 인덱싱 기능을 제공하는 Item[TKey]을 기본 속성으로 구현합니다.Visual Basic implements Item[TKey] as a default property, which provides the same indexing functionality.

이 속성의 값을 설정 또는 가져오기는 O(1) 연산에 가깝습니다.Getting or setting the value of this property approaches an O(1) operation.

적용 대상

추가 정보