KeyValuePair<TKey,TValue> 結構

定義

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

C#
public struct KeyValuePair<TKey,TValue>
C#
public readonly struct KeyValuePair<TKey,TValue>
C#
[System.Serializable]
public struct KeyValuePair<TKey,TValue>

類型參數

TKey

索引鍵的類型。

TValue

值的類型。

繼承
KeyValuePair<TKey,TValue>
屬性

範例

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

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

C#
// 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);
}

備註

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

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

C#
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}

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

建構函式

KeyValuePair<TKey,TValue>(TKey, TValue)

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

屬性

Key

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

Value

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

方法

Deconstruct(TKey, TValue)

解構目前的 KeyValuePair<TKey,TValue>

ToString()

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

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱