我有一个类 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/