在 C# 中对比KeyValuePair<TKey, TValue> 和 IDictionary<TKey, TValue>

C# 中的 KeyValuePair<TKey, TValue> 和 IDictionary<TKey, TValue> 具有独特的用途并表现出不同的特征。

KeyValuePair<TKey, TValue> 的功能

KeyValuePair<TKey, TValue> 是存储单个键值对的数据结构。它属于 System.Collections.Generic 命名空间。

用法

  • 它用于表示单个键值对,通常在枚举的上下文中或当需要从方法返回多个值时。

  • 经常与实现键值对的集合一起使用,例如字典,但也可以单独使用。

不变性

创建后,KeyValuePair 的键和值无法修改,因为其属性是只读的(DotNetPerls)。

特性

  • Key:获取键值对中的键。
  • Value:获取键值对中的值。

注意: KeyValuePair<TKey, TValue> 可能包含重复的键。

例子

复制代码
// 导入 System.Windows 命名空间以使用 WPF 功能。
using System.Windows; 

// 导入 System.Collections.Generic 命名空间以使用泛型集合。
using System.Collections.Generic; 

// 导入 System 命名空间以使用基本功能,如 Console。
using System; 

// 定义应用程序的命名空间。
namespace KeyValuePairDictionaryExample 
{
    // MainWindow.xaml 的交互逻辑
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    // MainWindow 类继承自 Window,Window 是 WPF 窗口的基类。
    public partial class MainWindow : Window 
    {
        // MainWindow 的构造函数。
        public MainWindow() 
        {
            // 初始化组件(由 WPF 设计器生成)。
            InitializeComponent(); 
            // 调用方法生成并显示键值对列表。
            GenerateKeyValuePairList(); 
        }

        // 方法生成一个键值对列表。
        private void GenerateKeyValuePairList() 
        {
            // 创建一个存储 KeyValuePair<string, string> 对象的列表。
            List<KeyValuePair<string, string>> keyValuePairsList = new List<KeyValuePair<string, string>>();

            // 添加初始的键值对到列表中。
            keyValuePairsList.Add(new KeyValuePair<string, string>("firstKey", "First Value")); 
            // 添加第一个键值对。
            keyValuePairsList.Add(new KeyValuePair<string, string>("secondKey", "Second Value")); 
            // 添加第二个键值对。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Third Value")); 
            // 添加第三个键值对。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Fourth Value")); 
            // 添加第四个键值对,键与前一个相同。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Fifth Value")); 
            // 添加第五个键值对,键与前一个相同。
            keyValuePairsList.Add(new KeyValuePair<string, string>("thirdKey", "Sixth Value")); 
            // 添加第六个键值对,键与前一个相同。

            // 创建一个列表存储要添加的新键值对。
            List<KeyValuePair<string, string>> itemsToAddToExistingList = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("fourthKey", "Seventh Value"), 
                // 创建并添加第七个键值对。
                new KeyValuePair<string, string>("fifthKey", "Eighth Value") 
                // 创建并添加第八个键值对。
            };

            // 将新键值对添加到原始列表中。
            foreach (var kvp in itemsToAddToExistingList) 
            // 遍历每个新键值对。
            {
                keyValuePairsList.Add(kvp); 
                // 将当前键值对添加到原始列表中。
            }

            // 调用方法显示所有键值对。
            ShowKeyValuePairs(keyValuePairsList);
        }

        // 方法显示键值对。
        private void ShowKeyValuePairs(List<KeyValuePair<string, string>> keyValuePairsList) 
        {
            // 遍历列表中的每个键值对。
            foreach (KeyValuePair<string, string> kvp in keyValuePairsList) 
            {
                // 输出键值对到控制台。
                Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); 
            }
        }
    }
}

Dictionary<TKey, TValue> 的功能

Dictionary<TKey, TValue> 类负责管理一组键值对。它是 System.Collections.Generic 命名空间的一个组件。

用途

此类的主要用途是存储多个键值对,确保每个键都是唯一的。它提供了检索、添加和删除这些对的高效操作。

可变性

就可变性而言,您可以在字典中添加、删除和更新元素。

用法

当您需要管理数据集合时通常使用此类,其中每个元素由唯一的键标识。

例子

复制代码
using System;
// 导入 System 命名空间以使用基本功能,如 Console。

using System.Windows;
// 导入 System.Windows 命名空间以使用 WPF 功能。

using System.Collections.Generic;
// 导入 System.Collections.Generic 命名空间以使用泛型集合。

namespace KeyValuePairDisctionaryExample
// 定义应用程序的命名空间。
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    // MainWindow 类继承自 Window,Window 是 WPF 窗口的基类。
    {
        public MainWindow()
        // MainWindow 的构造函数。
        {
            InitializeComponent();
            // 初始化组件(由 WPF 设计器生成)。
            GenerateDictionary();
            // 调用方法生成并显示字典。
        }

        private void GenerateDictionary()
        // 方法生成一个字典。
        {
            Dictionary<string, string> dictCollection = new Dictionary<string, string>
            // 创建一个存储键值对的字典。
            {
                {"firstKey", "First Value"},
                // 添加第一个键值对。
                {"secondKey", "Second value"},
                // 添加第二个键值对。
                {"ThirdKey", "Third Value"},
                // 添加第三个键值对。
                {"FourthKey", "Fourth Value"}
                // 添加第四个键值对。
            };

            dictCollection.Add("FifthKey", "FifthValue");
            // 添加第五个键值对。

            if (dictCollection.ContainsKey("secondKey"))
            // 检查字典是否包含键 "secondKey"。
            {
                Console.WriteLine(dictCollection["secondKey"]);
                // 输出键 "secondKey" 对应的值:Second value。
            }

            foreach (var kvp in dictCollection)
            // 遍历字典中的每个键值对。
            {
                Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");
                // 输出键值对到控制台。
            }
        }
    }
}

注意:在字典中,不允许有重复的键。

相关推荐
棣廷8 分钟前
初识Python面向对象
java·开发语言
研☆香15 分钟前
js中 onload 事件的用法
开发语言·javascript·ecmascript
xiancai_xianyu39 分钟前
想把数据模型一次建完美再上AI?会一直卡在建模里
开发语言·人工智能·php·数据模型·语义层·本体建模·企业知识网络
(Charon)1 小时前
【C++】网络缓冲区设计(二):Ring Buffer环形缓冲区、head/tail与跨界读写
开发语言·c++
Java后端的Ai之路1 小时前
LangChain Deep Agents 从入门到企业实战
开发语言·人工智能·python·langchain·deepagents
海盗12341 小时前
微软技术周报 2026-08-31~09-07:GPT-6 Astra 登陆 Foundry、M365 全球认证故障复盘、C# 15 封闭层级
gpt·microsoft·c#
会飞的拖把1 小时前
Python文件操作详解:从文件读写到os、shutil模块实战
开发语言·python
RS迷途小书童1 小时前
Python 解析大疆无人机 SRT 字幕日志
开发语言·python·无人机
点心的游戏开发世界2 小时前
GDScript 入门笔记(十六):文件读写与数据持久化
开发语言·笔记·游戏引擎·godot
会飞的拖把2 小时前
Python序列详解:列表、元组、字符串的通用操作(超详细版)
开发语言·windows·python