c# - Dictionary.ContainsKey 行为不端 c#

标签 c# .net dictionary

我有一个类 Column

public class Column
{
    public int Id { get; private set; }
    public string Name { get; private set; }
    public EPersonalCharacteristicType Type { get; private set; }
    public Column MainColumn { get; private set; }
}

我在另一个类中有以下字段

Dictionary<Column, string> dictionary

在执行过程中,我发现这个字典 有一个奇怪的行为。当我输入时

dictionary.ContainsKey(dictionary.Keys.ToList()[1])

我得到了 false
这到底是怎么回事?

已更新
我的 Column 类有 GetHashCode 或 Equals 函数。以下是它们的实现:

public bool Equals(Column other)
{
    if (ReferenceEquals(null, other)) return false;
    if (ReferenceEquals(this, other)) return true;
    return other.Id == Id && Equals(other.Name, Name) && Equals(other.Type, Type) && Equals(other.MainColumn, MainColumn) && Equals(other.childColumns, childColumns);
}

public override bool Equals(object obj)
{
    if (ReferenceEquals(null, obj)) return false;
    if (ReferenceEquals(this, obj)) return true;
    if (obj.GetType() != typeof (Column)) return false;
    return Equals((Column) obj);
}

public override int GetHashCode()
{
    unchecked
    {
        int result = Id;
        result = (result*397) ^ (Name != null ? Name.GetHashCode() : 0);
        result = (result*397) ^ Type.GetHashCode();
        result = (result*397) ^ (MainColumn != null ? MainColumn.GetHashCode() : 0);
        result = (result*397) ^ (childColumns != null ? childColumns.GetHashCode() : 0);
        return result;
    }
}

public static bool operator ==(Column left, Column right)
{
    return Equals(left, right);
}

public static bool operator !=(Column left, Column right)
{
    return !Equals(left, right);
}

最佳答案

这不是一般问题,而是您的代码所特有的问题。

更新:
字典键的哈希码不能改变。这不是您的 Column 类的情况,因为只要它的任何属性发生变化,散列码也会发生变化。
Documentation :

As long as an object is used as a key in the Dictionary, it must not change in any way that affects its hash value.

这件事的背景是这样的: 字典在添加时检索并存储键的哈希码。如果此后 key 的哈希码发生变化,则它与存储的哈希码不同,对象将不会被视为等于最初插入的 key 。

关于c# - Dictionary.ContainsKey 行为不端 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6437555/

相关文章:

c# - 处理异步并行任务的多个异常

c# - 是否可以迭代Asp.Net Web服务中的循环

c# - 如何在 IIS 中显示详细的堆栈跟踪?

.net - 提单服务 : Exception or Method Result?

python - 从列表中填充字典值

c# - itextsharp 5.5.5 textcolor 属性被删除

.net - 为什么 TimeSpan.FromSeconds(double) 四舍五入到毫秒?

c# - IList<IClient> 方法<T>() 其中 T : Iclient can not add client object to list

javascript - 多维数组分割成对象javascript

algorithm - 从子树中查找所需的最少字符