KeyValuePair<TKey,TValue> 結構

定義

定義可設定或擷取的索引鍵/值組。

generic <typename TKey, typename TValue>
public value class KeyValuePair
public struct KeyValuePair<TKey,TValue>
public readonly struct KeyValuePair<TKey,TValue>
[System.Serializable]
public struct KeyValuePair<TKey,TValue>
type KeyValuePair<'Key, 'Value> = struct
[<System.Serializable>]
type KeyValuePair<'Key, 'Value> = struct
Public Structure KeyValuePair(Of TKey, TValue)

類型參數

TKey

索引鍵的類型。

TValue

值的類型。

繼承
KeyValuePair<TKey,TValue>
屬性

範例

下列程式碼範例示範如何使用 結構列舉字典 KeyValuePair<TKey,TValue> 中的索引鍵和值。

此程式碼是提供給 類別之較大範例的 Dictionary<TKey,TValue> 一部分。

// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console::WriteLine();
for each( KeyValuePair<String^, String^> kvp in openWith )
{
    Console::WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}",
        kvp.Key, kvp.Value);
}
' When you use foreach to enumerate dictionary elements,
' the elements are retrieved as KeyValuePair objects.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
    Console.WriteLine("Key = {0}, Value = {1}", _
        kvp.Key, kvp.Value)
Next kvp

備註

屬性會 Dictionary<TKey,TValue>.Enumerator.Current 傳回這個類型的實例。

foreachC++ 中 C# 語言 (for each 的語句, For Each 在 Visual Basic 中) 會傳回集合中專案類型的 物件。 由於根據 IDictionary<TKey,TValue> 集合的每個元素都是索引鍵/值組,所以專案類型不是索引鍵的類型或值的型別。 相反地,元素類型為 KeyValuePair<TKey,TValue> 。 例如:

for each(KeyValuePair<String^, String^> kvp in myDictionary)
{
    Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of String, String) In myDictionary
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp

語句 foreach 是列舉值周圍的包裝函式,只允許讀取集合,而不允許寫入集合。

建構函式

KeyValuePair<TKey,TValue>(TKey, TValue)

使用指定的索引鍵和值,初始化 KeyValuePair<TKey,TValue> 結構的新執行個體。

屬性

Key

取得索引鍵/值組中的索引鍵。

Value

取得索引鍵/值組中的值。

方法

Deconstruct(TKey, TValue)

解構目前的 KeyValuePair<TKey,TValue>

ToString()

使用索引鍵和值的字串表示,傳回 KeyValuePair<TKey,TValue> 的字串表示。

適用於

另請參閱