이 클래스에서보세요 :IEqualityComparer 이상한 결과
public class MemorialPoint:IMemorialPoint,IEqualityComparer<MemorialPoint>
{
private string _PointName;
private IPoint _PointLocation;
private MemorialPointType _PointType;
private DateTime _PointStartTime;
private DateTime _PointFinishTime;
private string _NeighborName;
private double _Rms;
private double _PointPdop;
private double _PointHdop;
private double _PointVdop;
// getters and setters omitted
public bool Equals(MemorialPoint x, MemorialPoint y)
{
if (x.PointName == y.PointName)
return true;
else if (x.PointName == y.PointName && x.PointLocation.X == y.PointLocation.X && x.PointLocation.Y == y.PointLocation.Y)
return true;
else
return false;
}
public int GetHashCode(MemorialPoint obj)
{
return (obj.PointLocation.X.ToString() + obj.PointLocation.Y.ToString() + obj.PointName).GetHashCode();
}
}
또한 단지 두 지점 및 일부 다른 부가 요소 인 벡터 클래스를 가지고있다. 내 벡터에 동일한 포인트를 갖고 싶어하지 않는, 그래서 나는이 방법을 함께했다 :
[TestMethod]
[ExpectedException(typeof(ArgumentException), Messages.VectorWithEqualPoints)]
public void TestMemoriaVector_EqualPoints()
{
IPoint p1 = PointPolygonBuilder.BuildPoint(0, 0);
IPoint p2 = PointPolygonBuilder.BuildPoint(0, 0);
IMemorialPoint mPoint1 = new MemorialPoint("teste1", p1);
IMemorialPoint mPoint2 = new MemorialPoint("teste1", p2);
Console.WriteLine(mPoint1.GetHashCode().ToString());
Console.WriteLine(mPoint2.GetHashCode().ToString());
vector = new MemorialVector(mPoint1, mPoint1, 0);
}
내가 사용 : 나에게 예외를 제공해야합니다
public void RecalculateVector(IMemorialPoint fromPoint, IMemorialPoint toPoint, int partIndex)
{
if (fromPoint.Equals(toPoint))
throw new ArgumentException(Messages.VectorWithEqualPoints);
this.FromPoint = FromPoint;
this.ToPoint = ToPoint;
this.PartIndex = partIndex;
// the constructDifference method has a weird way of working:
// difference of Point1 and Point 2, so point2 > point1 is the direction
IVector3D vector = new Vector3DClass();
vector.ConstructDifference(toPoint.PointLocation, fromPoint.PointLocation);
this.Azimuth = MathUtilities.RadiansToDegrees(vector.Azimuth);
IPointCollection pointCollection = new PolylineClass();
pointCollection.AddPoint(fromPoint.PointLocation, ref _missing, ref _missing);
pointCollection.AddPoint(toPoint.PointLocation, ref _missing, ref _missing);
this._ResultingPolyline = pointCollection as IPolyline;
}
그리고이 단위 테스트, 같은 점, 즉 mPoint1, 예외가 throw 된 코드와 같습니다. mPoint2를 사용할 때 이름과 좌표가 같아도 예외는 발생하지 않습니다. 해시 코드를 확인한 결과 사실상 다릅니다. GetHashCode에서 만든 코드를 기반으로이 두 점은 동일한 해시 코드를가집니다.
누군가 내가 왜 그렇게 행동하지 않는지 설명 할 수 있습니까? 내가 잘 설명 모르겠지만, .. 내가 도움을 주셔서 감사합니다 : D를
조지
설명 주셔서 대단히 감사합니다. 문서가 아니라. 당신이 말하는 것처럼, IEqualityComparer, IEqualityComparer , IEqualityComparer 을 구현할 수 있습니다. 감사합니다. –
@ 조지 : 주목할 가치가있는 한 가지 점은 평등 비교자는 다른 값을 비교하는 것보다 * 다른 *을 할 의도가 거의 없다는 것입니다. 그것은 대개 자신의 책임이어야합니다. –