📜  演示 IDictionary 接口的 C# 程序(1)

📅  最后修改于: 2023-12-03 15:27:04.058000             🧑  作者: Mango

演示 IDictionary 接口的 C# 程序

IDictionary 是 C# 中的一个接口,它允许开发人员使用键-值对存储和检索数据。在这个程序中,我们将演示如何使用 IDictionary 接口。

示例代码
using System;
using System.Collections;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个 IDictionary 对象
        IDictionary numbers = new Hashtable();

        // 添加键值对
        numbers.Add("one", 1);
        numbers.Add("two", 2);
        numbers.Add("three", 3);

        // 访问键值对
        Console.WriteLine("The value of 'one' is {0}.", numbers["one"]);
        Console.WriteLine("The value of 'two' is {0}.", numbers["two"]);
        Console.WriteLine("The value of 'three' is {0}.", numbers["three"]);

        // 修改键值对
        numbers["one"] = 10;
        Console.WriteLine("The value of 'one' is now {0}.", numbers["one"]);

        // 删除键值对
        numbers.Remove("two");
        Console.WriteLine("The 'two' key is now removed.");

        // 遍历所有键值对
        foreach (DictionaryEntry entry in numbers)
        {
            Console.WriteLine("Key = {0}, Value = {1}", entry.Key, entry.Value);
        }

        // 清除所有键值对
        numbers.Clear();
        Console.WriteLine("All key-value pairs are now cleared.");

        Console.ReadLine();
    }
}
示例说明
  1. 首先,我们使用 Hashtable 类创建了一个名为 numbers 的 IDictionary 对象。注意,我们也可以使用其他实现了 IDictionary 接口的类,例如 SortedDictionary 或 Dictionary。
  2. 使用 Add 方法向 numbers 中添加了三个键值对。在这里,我们使用字符串作为键,整数作为值。
  3. 使用索引器访问键值对。我们可以像这样使用键来获取值:numbers["one"]
  4. 使用索引器修改键值对的值:numbers["one"] = 10
  5. 使用 Remove 方法删除一个键值对:numbers.Remove("two")
  6. 使用 foreach 循环遍历所有键值对并输出它们的键和值:foreach (DictionaryEntry entry in numbers)
  7. 使用 Clear 方法清除所有键值对:numbers.Clear()
示例输出

输出如下:

The value of 'one' is 1.
The value of 'two' is 2.
The value of 'three' is 3.
The value of 'one' is now 10.
The 'two' key is now removed.
Key = one, Value = 10
Key = three, Value = 3
All key-value pairs are now cleared.
总结

本示例展示了使用 IDictionary 接口的基本操作。对 IDictionary 接口的理解会帮助开发人员更好地管理和操作键值对数据。请注意,IDictionary 是一个接口,实际上我们使用的是它的实现类,例如 Hashtable。此外,C# 中还有许多其他有用的接口和类可用于处理键值对数据,如 SortedDictionary 和 Dictionary。