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 返回此类型的实例。

foreach C++ 中的 C# 语言 (for eachFor 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> 的字符串表示形式。

适用于

另请参阅