📅  最后修改于: 2023-12-03 15:27:04.058000             🧑  作者: Mango
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();
}
}
numbers["one"]
。numbers["one"] = 10
。numbers.Remove("two")
。foreach (DictionaryEntry entry in numbers)
。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。