一个非常奇怪的System.Collections.Generic.KeyNotFoundException在字典中

本文关键字:Generic Collections System KeyNotFoundException 字典 一个 非常 | 更新日期: 2023-09-27 18:17:48

我的代码中有一个奇怪的错误…

代码:

public class PropertyCollection<T> : IDictionary<T, string>
{
        private Dictionary<T, string> dict;
        ...
        public string this[T key]
        {
            get
            {
                bool has_key = this.Keys.Any(x => x == key); 
                return this.dict[key];
            }
            set
            {
                this.dict[key] = value;
            }
        }
        ...
}

第一行

bool has_key = this.Keys.Any(x => x == key);

返回true

,

return this.dict[key];

抛出错误:

System.Collections.ListDictionaryInternal。NodeKeyValueCollection:给定的键不存在于字典中。

这怎么可能?

如果我更改行,会抛出异常,到

return this.dict[this.Keys.First(x => x == key)];  

一切正常,现在有错误。

一个非常奇怪的System.Collections.Generic.KeyNotFoundException在字典中

假设T覆盖EqualsGetHashCode *,我能想到的唯一方法是如果你的键是可变的,它的GetHashCode方法使用可变字段,并且在键被插入字典后调用一个突变方法

这将使线性搜索this.Keys.Any(x => x == key)产生true,但是基于哈希的搜索将产生一个异常。

确认这很容易:下面的代码应该打印false:

var first = dict.Keys.First(x => x == key);
Console.WriteLine(first.GetHashCode() == key.GetHashCode());

*如果T没有覆盖这些方法中的一个或两个,请参阅此问题& a。

相关文章: