我尝试实现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
类的专有StreetCode
和BuildingNumber
是整数,Address
就可以完美。
但是,如果我需要将StreetCode
类中的属性类型BuildingNumber
和Address
更改为字符串,该怎么办?
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
方法?