Dictionary<TKey,TValue>.Item[TKey] 속성
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
지정된 키와 연결된 값을 가져오거나 설정합니다.
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
가져오기 또는 설정할 값의 키입니다.
속성 값
지정된 키와 연결된 값입니다. 지정된 키를 찾을 수 없으면 get 작업이 throw KeyNotFoundException되고 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 =
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.
let openWith = 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")
with :? ArgumentException ->
printfn "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.
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 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
printfn $"""For key = "tif", value = {openWith["tif"]}"""
with :? KeyNotFoundException ->
printfn "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", 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.
match openWith.TryGetValue "tif" with
| true, value -> printfn $"For key = \"tif\", value = {value}."
| _ -> printfn "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](Visual Basic myCollection(key)).
에 없는 Dictionary<TKey,TValue>키의 값을 설정 하 여 새 요소를 추가 하는 속성을 사용할 Item[] 수도 있습니다. 속성 값을 설정할 때 키가 있는 Dictionary<TKey,TValue>경우 해당 키와 연결된 값이 할당된 값으로 대체됩니다. 키가 없는 Dictionary<TKey,TValue>경우 키와 값이 사전에 추가됩니다. 반면, 메서드는 Add 기존 요소를 수정하지 않습니다.
키는 사용할 null수 없지만 값 형식이 참조 형식 TValue 인 경우 값이 될 수 있습니다.
C# 언어는 키워드를 this 사용하여 속성을 구현하는 대신 인덱서를 정의합니다 Item[] . Visual Basic은 Item[] 동일한 인덱싱 기능을 제공하는 기본 속성으로 구현합니다.
이 속성의 값을 가져오거나 설정하면 O(1) 작업에 접근합니다.