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

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

相关推荐
向阳开的夏天7 小时前
麒麟V10源码编译QT5.6.3 (x86 & arm64)
开发语言·qt
Evand J7 小时前
【MATLAB例程】TOA和TDOA混合定位,适用于二维平面的高精度定位。锚点数量、位置、测量噪声可自行调节
开发语言·matlab·定位·tdoa
念越7 小时前
数据结构:栈堆
java·开发语言·数据结构
淮北4948 小时前
pip虚拟环境包的问题
开发语言·python·pip
dear_bi_MyOnly8 小时前
【多线程——线程状态与安全】
java·开发语言·数据结构·后端·中间件·java-ee·intellij-idea
常年游走在bug的边缘8 小时前
掌握JavaScript作用域:从函数作用域到块级作用域的演进与实践
开发语言·前端·javascript
jiaguangqingpanda8 小时前
Day36-20260204
java·开发语言
ctyshr8 小时前
C++编译期数学计算
开发语言·c++·算法
打码的猿8 小时前
Qt对话框不锁死主程序的方法
开发语言·qt
努力写代码的熊大8 小时前
c++异常和智能指针
java·开发语言·c++