C# 如何更改哈希代码?
我有一个创建对象的类:C# 如何更改哈希代码?,c#,hashset,gethashcode,C#,Hashset,Gethashcode,我有一个创建对象的类: 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)); } } 和班犬: pub
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));
}
}
和班犬:
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;
}
}
}
然后,在另一个类中,我在hashset中添加了创建的Dog对象。
我需要通过从Creator类更改Dog类的对象,使hashset停止正常工作。我怎样才能做到这一点呢?您的对象不是不可变的,您正在使用它作为
哈希集的“键”
。。。这是在找麻烦
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
Dog-Dog=Create();
HashSet dogs=新HashSet();
狗。添加(狗);
Console.WriteLine(dogs.Contains(dog));//真的
狗。更改名称(“Foo”);
Console.WriteLine(dogs.Contains(dog));//假的
如果更改其中一个属性,则在将对象插入
HashSet
后,将根据计算GetHashCode()
,您将“破坏”HashSet我需要使HashSet停止正常工作
-真的吗?你需要它来停止正常工作吗?通过允许在使用该值计算hashcode时更改名称,您正是实现了这一点。如何从Creator类更改Dog字段?我需要在“DoSomething”中这样做method@Maxter你不能。“正确”的方法是从HashSet
中删除该项,对其进行修改,然后将其读取到HashSet
。HashSet
“缓存”其项的GetHashCode()
。“正确”的方法是不要将GetHashCode()
基于可变字段。例如,您可以仅根据生日
(在代码中创建后无法修改)谢谢,现在我更好地理解了GetHashCode
的工作。但我的任务是使哈希集工作不正确,我只能更改Creator类的结构。@Maxter如果您在DoSomething()
中修改dog
,则hashset
将“不正确地”工作(根据其规范,它将正常工作,从门外汉的角度来看是不正确的)