C# Dictionary<TKey, TValue>

命名空间:System.Collections.Generic

基本等同于 Java 的 HashMap<T>

构造函数

  • Dictionary<TKey, TValue>():默认初始容量,使用键类型的默认相等比较器。
  • Dictionary<TKey, TValue>(IDictionary<TKey, TValue>):从某字典中复制元素,使用默认初始容量,使用键类型的默认相等比较器。
  • Dictionary<TKey, TValue>(IDictionary<TKey, TValue>, IEqualityComparer<TKey>):从某字典中复制元素,使用默认初始容量,使用指定的相等比较器。
  • Dictionary<TKey, TValue>(IEqualityComparer<TKey>):使用默认初始容量,使用指定的相等比较器。
  • Dictionary<TKey, TValue>(Int32)指定初始容量,使用键类型的默认相等比较器。
  • Dictionary<TKey, TValue>(Int32, IEqualityComparer<TKey>)指定初始容量,使用指定的相等比较器。

属性

  • Comparer:获取比较器对象。
  • Count:获取键值对数目。
  • Keys:获取键的集合。
  • Values:获取值的集合。

方法

  • Add(TKey, TValue):将指定的键和值添加到字典中。
  • Clear():移除所有键与值。
  • ContainsKey(TKey):确定字典中是否包含指定键。
  • ContainsValue(TValue):确定字典中是否包含指定值。
  • Remove(TKey):从字典中移除指定的键的值。

其他

  • 直接使用 [] 获取或设置指定键的值。要求指定键已经存在于字典中。

注意点

在存入键值对后,不要修改存入的 Key。具体来说,不要修改 Key 后影响 HashCode 的计算。否则可能会产生异常。

Dictionary<TestClass, int> map = new Dictionary<TestClass, int>();
TestClass t1 = new TestClass() { X = 1, Y = 2 };
TestClass t2 = new TestClass() { Y = 3, X = 4 };
TestClass t3 = new TestClass() {  Y = 1, X = 2 };

map.Add(t1, 1);
map.Add(t2, 2);

t1.X = 100;
// Console.WriteLine(map[t1]); // 给定关键字不在字典中

map.Add(t3, 3);
Console.WriteLine(map.Count); // 3

具体来说,在存入时,字典按照 KeyHashCode 将键值对(KeyValuePair<TKey, TValue>)存入指定位置。在修改 Key 导致 HashCode 更改后,字典不会对键值对存入位置作出更新,所以通过原来的 Key 对象获取元素时,无法从新的 HashCode 的位置读取到原来的键值对。

线程安全

ConcurrentDictionary<TKey,TValue>

posted @ 2025-08-19 22:04  Varc  阅读(1)  评论(0)    收藏  举报