我在相等和向字典中添加对象时遇到问题
class DoublePoint
{
public double X;
public double Y;
public double Z;
public DoublePoint(double x, double y, double z)
{
this.X = x; this.Y = y; this.Z = z;
}
public override bool Equals(object obj)
{
try
{
DoublePoint dPoint = obj as DoublePoint;
return this.X.IsEqualTo(dPoint.X) && this.Y.IsEqualTo(dPoint.Y) && this.Z.IsEqualTo(dPoint.Z);
}
catch
{
throw;
}
}
public override int GetHashCode()
{
return this.X.GetCode() ^ this.Y.GetCode() ^ this.Z.GetCode();
}
}
static class extensions
{
static double Tolerance = 0.001;
public static bool IsEqualTo(this double d1, double d2)
{
return (d1 - d2) <= Tolerance;
}
public static int GetCode(this double d1)
{
byte[] data = BitConverter.GetBytes(d1);
int x = BitConverter.ToInt32(data, 0);
int y = BitConverter.ToInt32(data, 4);
return x ^ y;
}
}
这是我的测试:
DoublePoint d1 = new DoublePoint(1.200, 2.3, 3.4);
DoublePoint d2 = new DoublePoint(1.2001, 2.3, 3.4);
DoublePoint d3 = new DoublePoint(1.200, 2.3, 3.4);
bool isEqual = d1.Equals(d2); // true here
Dictionary<DoublePoint, int> dict = new Dictionary<DoublePoint, int>();
dict.Add(d1, 1);
dict.Add(d2, 2); // successful, d2 is also added but d2 is equal to d1
dict.Add(d3, 3); // Error! since we have d1 already in dictionary
有了这个,
当我添加相同的双点对象(具有一定的公差)时,我可以将它们添加到字典中。如何限制此类对象。
是比较具有一定公差的双重数据类型的正确方法。
请指教。
谢谢