要将您的类型用作字典键,您应该重写两种方法:GetHashCode
和Equals
.
默认情况下(如果您不覆盖GetHashCode
)您类型的每个对象(即使具有相同的字段值)都将返回唯一值。这意味着您将只能找到您将放入字典中的完全相同的“参考”。考虑以下两种类型:MyType1
不覆盖GetHashCode
andEquals
和 MyType2 :
class MyType1
{
public MyType1(int id, string name) {Id = id; Name = name;}
public int Id {get; private set;}
public string Name {get; private set;}
}
internal class MyType2
{
public MyType2(int id, string name)
{
Id = id;
Name = name;
}
public int Id { get; private set; }
public string Name { get; private set; }
bool Equals(MyType2 other)
{
return Id == other.Id && string.Equals(Name, other.Name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((MyType2) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Id*397) ^ Name.GetHashCode();
}
}
}
var d1 = new Dictionary<MyType1, int>();
d1[new MyType1(1, "1")] = 1;
d1[new MyType1(1, "1")]++; // will throw withKeyNotFoundException
var d2 = new Dictionary<MyType2, int>();
d1[new MyType2(1, "1")] = 1;
d1[new MyType2(1, "1")]++; // Ok, we'll find appropriate record in dictionary