【问题标题】:When using a class as key of dictionary: is there a possibility to specify which class property/ variable determines the key当使用类作为字典的键时:是否有可能指定哪个类属性/变量确定键
【发布时间】:2021-01-22 05:58:04
【问题描述】:

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

我的课程是例如:

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”当然是重复的,因为考虑到地址和所有者,如果一个人拥有多个房屋,则存在多个唯一的“密钥对”。

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

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

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

感谢您的支持和努力! :)

【问题讨论】:

标签: c# dictionary key


【解决方案1】:

如果您希望owner(在此简化代码中)成为您的DictionaryKey,您将需要覆盖EqualsGetHashCode。覆盖两者很重要,否则它将不起作用。

这里是 House 类的示例:
如果您创建具有相同所有者的两个房屋并尝试将它们添加到 KeyHouse object 它会给你一个错误

编辑
这是来自@l33t 的重要编辑:
“不要使用公共字段。而是使用带有私有设置器的属性。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
    }

【讨论】:

  • 如果在将对象添加到字典后更改Owner 会发生什么?
  • @l33t 嘿嘿。真的很好的问题!在我尝试之前我不知道答案...不幸的是字典没有通知更改并接受两个条目...关于如何解决它的任何想法?
  • 不要使用公共字段。而是使用带有私有设置器的属性。 GetHashCode() 中使用的任何值必须是不可变的,否则您的对象将丢失(例如字典),再也找不到了。
  • @l33t 我编辑了我的答案并添加了您的评论以及指向您个人资料的链接。非常讨厌你!
猜你喜欢
  • 2021-02-13
  • 2017-05-06
  • 1970-01-01
  • 2018-12-16
  • 2020-01-01
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多