当使用 class 作为字典的键时:是否可以指定哪个 class 属性/ 变量确定键

When using a class as key of dictionary: is there a possibility to specify which class property/ variable determines the key

我尝试使用简化的源代码来解释我的问题。

我的class例如:

public class House
{
  public House(...)
  {
    address = ...;
    owner = ...;
  }

  public string address; //Unique variable
 
  public string owner; //Not unique variable
}

在某些时候,我需要一本以“House”为键的字典,例如作为值的布尔值。 例如

var doesTheHouseOwnerHaveDept= new Dictionary<House,bool>();

然后,我的问题是字典“doesTheHouseOwnerHaveDept”当然充满了重复项,因为通过考虑地址和所有者,如果一个人拥有多个房屋,则存在多个唯一的“密钥对”。

因此,是否有可能修改class,以便仅class“house”中的“owner”变量用于指定字典“doesTheHouseOwnerHaveDept”的键?

即,当所有者例如“Max”拥有地址“A”和“B”的房子,然后,先到先得,只有一个“House”-实例将添加到字典“doesTheHouseOwnerHaveDept”中。

我知道在前面的例子中,问题可以通过其他更直观的方式轻松解决,但我没有更好的主意,并且想避免发布原始源代码。

感谢一百万的支持和努力! :)

如果您希望 owner(在此简化代码中)成为 DictionaryKey,则需要覆盖 EqualsGetHashCode.重要的是要覆盖两者,否则它将无法工作。

这里有一个例子 House class:
如果您创建两个拥有相同所有者的房子并尝试将它们添加到字典中,其中 KeyHouse 对象,它会给您一个错误

编辑
这是来自 @l33t 的重要编辑:
“不要使用 public 字段。而是使用带有私有 setter 的 属性。GetHashCode() 中使用的任何值都必须是不可变的,否则您的对象将丢失(例如在字典中),再也找不到了。"


public class House
{
    public House(string address, string owner)
    {
        this.Address = address;
        this.Owner = owner;
    }

    public string Address; //Unique variable

    public string Owner
    {
        get;
        private set; //Private setter so the owner can't be changed outside this class because it if changes and the object is already inside 
                        // a dictionary it won't get notified and there will be two objects with the same 'Key'

    }

    public override bool Equals(object obj)
    {
        if (!(obj is House)) return false;

        var toCompare = (House) obj;
        return this.Owner == toCompare.Owner; //Just compare the owner. The other properties (address) can be the same
    }

    public override int GetHashCode()
    {
        return Owner.GetHashCode(); //Just get hashcode of the owner. Hashcode from the address is irrelevant in this example
    }