SortedDictionary<TKey,TValue>.TryGetValue(TKey, TValue) 메서드

정의

지정한 키와 연결된 값을 가져옵니다.

public:
 virtual bool TryGetValue(TKey key, [Runtime::InteropServices::Out] TValue % value);
public bool TryGetValue (TKey key, out TValue value);
abstract member TryGetValue : 'Key * 'Value -> bool
override this.TryGetValue : 'Key * 'Value -> bool
Public Function TryGetValue (key As TKey, ByRef value As TValue) As Boolean

매개 변수

key
TKey

가져올 값의 키입니다.

value
TValue

이 메서드가 반환될 때 지정된 키가 있으면 해당 키와 연결된 값이고, 그렇지 않으면 value 매개 변수의 형식에 대한 기본값입니다.

반환

true에 지정한 키가 있는 요소가 포함되어 있으면 SortedDictionary<TKey,TValue>이고, 그렇지 않으면 false입니다.

구현

예외

key이(가) null인 경우

예제

이 예제에서는 사전에 없는 키를 자주 시도하는 프로그램에서 값을 검색하는 보다 효율적인 방법으로 메서드를 사용하는 TryGetValue 방법을 보여줍니다. 반면에 이 예제에서는 존재하지 않는 키를 검색하려고 할 때 속성(C#의 인덱서)이 예외를 throw하는 방법 Item[] 도 보여 줍니다.

이 코드 예제는에 대해 제공 된 큰 예제의 일부는 SortedDictionary<TKey,TValue> 클래스입니다.

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

설명

이 메서드는 메서드와 속성의 ContainsKey 기능을 결합합니다 Item[] .

키를 찾을 value 수 없는 경우 매개 변수는 값 형식에 대한 적절한 기본값을 가져옵니다. 예를 들어 정수 형식 TValue의 경우 0, false 부울 형식의 경우 및 null 참조 형식의 경우 0입니다.

이 메서드는 O(log n) 작업입니다.

적용 대상

추가 정보