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

정의

지정된 키에 연결된 값을 가져오거나 설정합니다.

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

가져오거나 설정할 값의 키입니다.

속성 값

TValue

지정한 키와 연결된 값입니다. 지정한 키가 없으면 get 작업에서 KeyNotFoundException을 throw하고 set 작업에서 지정한 키가 있는 새 요소를 만듭니다.

구현

예외

key이(가) null인 경우

속성을 검색할 때 컬렉션에 key가 없는 경우

예제

다음 코드 예제에서는 속성(C#의 인덱서)을 사용하여 Item[] 값을 검색하고 요청된 키가 없을 때 throw됨을 KeyNotFoundException 보여 주고 키와 연결된 값을 바꿀 수 있음을 보여 줍니다.

또한 프로그램에서 사전에 없는 키 값을 자주 시도해야 하는 경우 이 메서드를 보다 효율적인 방법으로 사용하여 TryGetValue 값을 검색하는 방법도 보여 있습니다.

이 코드 예제는에 대해 제공 된 큰 예제의 일부는 Dictionary<TKey,TValue> 클래스입니다. openWith 는 이 예제에 사용된 사전의 이름입니다.

// 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)을 사용하여 컬렉션의 특정 요소에 액세스할 수 있는 기능을 제공합니다.

에 없는 Dictionary<TKey,TValue>키의 값을 설정 하 여 새 요소를 추가 하려면 속성을 사용할 Item[] 수도 있습니다. 속성 값을 설정할 때 키가 있는 Dictionary<TKey,TValue>경우 해당 키와 연결된 값이 할당된 값으로 바뀝 있습니다. 키가 없는 Dictionary<TKey,TValue>경우 키와 값이 사전에 추가됩니다. 반면, 메서드는 Add 기존 요소를 수정하지 않습니다.

키는 사용할 null수 없지만 값 형식이 참조 형식 TValue 인 경우 값이 될 수 있습니다.

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

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

적용 대상

추가 정보