[英]Puzzling behaviour in IEqualityComparer<T>, breakpoint in the Equals() method is not hit
[英]Breakpoint in Equals implimentation on IEqualityComparer<CustomClass> is never hit
我有一个简单的自定义 class 点:
public class Point: IEqualityComparer<Point>
{
public double X;
public double Y;
public double Z;
private double[] startPointCoords;
public Point()
{
}
public Point(double[] pointArray)
{
this.startPointCoords = pointArray;
X = pointArray[0];
Y = pointArray[1];
Z = pointArray[2];
}
public bool Equals(Point x, Point y)
{
if(x.X == y.X && x.Y == y.Y && x.Z == y.Z)
{
return true;
}
return false;
}
public int GetHashCode(Point obj)
{
string xString = X.ToString().Replace(".", "");
string yString = Y.ToString().Replace(".", "");
string zString = Z.ToString().Replace(".", "");
int xInt = Convert.ToInt32(xString);
int yInt = Convert.ToInt32(yString);
int zInt = Convert.ToInt32(zString);
return xInt - yInt + zInt;
}
}
我在字典中使用这个 class 。 我正在使用以下方法检查点实例是否已添加到字典中:
if (!pointsToProcess.ContainsKey(startPoint))
{
pointsToProcess.Add(startPoint, startPoint);
}
我正在调试我的代码以确保 Equals 正常工作。 我在 Point.Equals 中设置的断点永远不会被击中。 我在 Point.GetHashCode 中设置了一个断点,它也从未被击中。 似乎它们没有被使用。
我知道有一些类叫做 Point in.Net。 我绝对确定我的代码中的所有点都来自我的自定义命名空间。
为什么设置断点时无法达到我的 Point.Equals 和 Point.GetHashCode?
Equals(a, b)
方法不受IEquatable
的影响,因此您需要对其进行定制以适应界面。
试试这个:
public class Point : IEquatable<Point>
{
public double X;
public double Y;
public double Z;
private double[] startPointCoords;
public Point()
{
}
public Point(double[] pointArray)
{
this.startPointCoords = pointArray;
X = pointArray[0];
Y = pointArray[1];
Z = pointArray[2];
}
public override bool Equals(object obj) => Equals(obj as Point);
public bool Equals(Point other)
{
if (other is null)
return false;
if (ReferenceEquals(this, other))
return true;
return this.X == other.X &&
this.Y == other.Y &&
this.Z == other.Z;
}
public override int GetHashCode()
{
string xString = X.ToString().Replace(".", "");
string yString = Y.ToString().Replace(".", "");
string zString = Z.ToString().Replace(".", "");
int xInt = Convert.ToInt32(xString);
int yInt = Convert.ToInt32(yString);
int zInt = Convert.ToInt32(zString);
return xInt - yInt + zInt;
}
}
还有很多方法可以在 C# 中为自定义对象实现哈希码。 虽然并不完美,但一种简单的方法是使用匿名 object 散列:
public override int GetHashCode()
{
return new { X, Y, Z }.GetHashCode();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.