如何正确实现GetHashCode方法?

时间:2017-11-06 13:33:11

标签: c# .net

我尝试实现IEqualityComparer:

class AddressComparer : IEqualityComparer<Address>
{
    #region IEqualityComparer<Address> Members

    public bool Equals(Address x, Address y)
    {
       return (x.CurrentBuildingNumber == y.CurrentBuildingNumber) && (x.CurrentBuildingLetter == y.CurrentBuildingLetter);
    }

    public int GetHashCode(Address obj)
    {
        return obj.StreetCode1 + obj.StreetCode2 + obj.BuildingNumber1 + obj.BuildingNumber2;
    }

    #endregion
}

这是地址类:

public class Address : IComparable
{   
    public int StreetCode1   { get; set; }
    public int BuildingNumber1 { get; set; }
    public string BuildingLetter1 { get; set; }

    public int StreetCode2 { get; set; }
    public int BuildingNumber2 { get; set; }
    public string BuildingLetter2 { get; set; }

}

如果AddressComparer类的专有StreetCodeBuildingNumber是整数,Address就可以完美。

但是,如果我需要将StreetCode类中的属性类型BuildingNumberAddress更改为字符串,该怎么办?

public class Address : IComparable
{   
    public string StreetCode1 { get; set; }
    public string BuildingNumber1 { get; set; }
    public string BuildingLetter1 { get; set; }

    public string StreetCode2 { get; set; }
    public string BuildingNumber2 { get; set; }
    public string BuildingLetter2 { get; set; }

}

以下是新AddressComparer

的实现
class AddressComparer : IEqualityComparer<Address>
{
    #region IEqualityComparer<Address> Members

    public bool Equals(Address x, Address y)
    {
       return String.Compare(x.CurrentBuildingNumber, y.CurrentBuildingNumber) && (x.CurrentBuildingLetter, y.CurrentBuildingLetter)
    }

    public int GetHashCode(Address obj)
    {
        //how to implement?
    }

    #endregion
}

如果我的专长是字符串,我该如何实现GetHashCode方法?

0 个答案:

没有答案