在 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}");
                // 输出键值对到控制台。
            }
        }
    }
}

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

相关推荐
isyangli_blog12 小时前
OpenDayLight (Carbon 版本) 启动与组件安装
开发语言·php
vb20081112 小时前
FastAPI APIRouter
开发语言·python
Benszen12 小时前
KVM虚拟化解决方案
开发语言·perl
会编程的土豆12 小时前
Go 语言反射(Reflection)详解
开发语言·后端·golang
東雪木12 小时前
多线程与并发编程 专属复习笔记
java·开发语言·笔记·java面试
杨充12 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
噜噜噜阿鲁~12 小时前
python学习笔记 | 11.3、面向对象高级编程-多重继承
java·开发语言
basketball61613 小时前
Go 语言从入门到进阶:4. 数组和MAP使用方法总结
开发语言·后端·golang
春生野草13 小时前
反射、Tomcat执行
java·开发语言
雪的季节14 小时前
企业级 Qt 全功能项目
开发语言·数据库·qt