如何更改哈希码?
How to change the hashcode?
我有一个 class 创建对象:
public class Creator
{
public void DoSomething()
{
//I need to change the field of the Dog class here
}
public Dog Create()
{
return new Dog("Buddy", new DateTime(2000, 9, 29));
}
}
和class狗:
public class Dog
{
public string Name { get; private set; }
public DateTime BirthDate { get; private set; }
public Dog(string name, DateTime birthDate)
{
Name = name;
BirthDate = birthdate;
}
protected bool Equals(Dog other)
{
return Name.Equals(other.Name)
&& BirthDate.Equals(other.BirthDate);
}
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((Dog) obj);
}
public override int GetHashCode()
{
return unchecked(Name.GetHashCode()*397
^ BirthDate.GetHashCode());
}
public void ChangeName(string name)
{
Name = name;
}
}
}
然后,在另一个 class 中,我在哈希集中添加创建的 Dog 对象。
我需要通过从 Creator class 更改 Dog class 的对象来使 hashset 停止正常工作。我该怎么做?
您的对象不是不可变的,您将其用作 HashSet<>
的 "key"...这是自找麻烦...
Dog dog = Create();
HashSet<Dog> dogs = new HashSet<Dog>();
dogs.Add(dog);
Console.WriteLine(dogs.Contains(dog)); // True
dog.ChangeName("Foo");
Console.WriteLine(dogs.Contains(dog)); // False
如果您更改其中一个属性,GetHashCode()
是根据 在 将对象插入 HashSet<>
之后计算得出的,您将 "break" HashSet<>
.
我有一个 class 创建对象:
public class Creator
{
public void DoSomething()
{
//I need to change the field of the Dog class here
}
public Dog Create()
{
return new Dog("Buddy", new DateTime(2000, 9, 29));
}
}
和class狗:
public class Dog
{
public string Name { get; private set; }
public DateTime BirthDate { get; private set; }
public Dog(string name, DateTime birthDate)
{
Name = name;
BirthDate = birthdate;
}
protected bool Equals(Dog other)
{
return Name.Equals(other.Name)
&& BirthDate.Equals(other.BirthDate);
}
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((Dog) obj);
}
public override int GetHashCode()
{
return unchecked(Name.GetHashCode()*397
^ BirthDate.GetHashCode());
}
public void ChangeName(string name)
{
Name = name;
}
}
}
然后,在另一个 class 中,我在哈希集中添加创建的 Dog 对象。 我需要通过从 Creator class 更改 Dog class 的对象来使 hashset 停止正常工作。我该怎么做?
您的对象不是不可变的,您将其用作 HashSet<>
的 "key"...这是自找麻烦...
Dog dog = Create();
HashSet<Dog> dogs = new HashSet<Dog>();
dogs.Add(dog);
Console.WriteLine(dogs.Contains(dog)); // True
dog.ChangeName("Foo");
Console.WriteLine(dogs.Contains(dog)); // False
如果您更改其中一个属性,GetHashCode()
是根据 在 将对象插入 HashSet<>
之后计算得出的,您将 "break" HashSet<>
.