.net的Doctionary类
时间: 2024-05-12 07:18:52 浏览: 8
Dictionary类是C#中的一种泛型集合类型,它允许您使用键值对来存储和访问数据。它是System.Collections.Generic命名空间中的一部分。
Dictionary类是一种哈希表数据结构,它使用键来查找和访问值。键必须是唯一的,而值可以重复。Dictionary类提供了以下方法:
1. Add:向字典中添加一个键值对。
2. Remove:从字典中移除指定键的键值对。
3. ContainsKey:确定字典是否包含指定键。
4. TryGetValue:获取与指定键关联的值。
5. Clear:从字典中移除所有键值对。
6. Count:获取字典中键值对的数量。
Dictionary类还提供了一些属性,如Keys和Values,它们分别返回字典中所有的键和所有的值。
下面是一个示例,展示如何使用Dictionary类:
```
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("apple", 1);
dict.Add("banana", 2);
dict.Add("cherry", 3);
Console.WriteLine(dict.ContainsKey("banana")); // 输出 True
int value;
if (dict.TryGetValue("apple", out value))
{
Console.WriteLine(value); // 输出 1
}
foreach (string key in dict.Keys)
{
Console.WriteLine(key + ": " + dict[key]);
}
}
}
```