我有一個平等和添加對象的問題,以字典忽略equals和GetHashCode和雙比較
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
有了這個,
當我添加相同的(具有一定寬容)的雙點對象時,我可以將它們添加到字典中。如何限制這些對象。
是將雙數據類型與一些容差進行比較的正確方法。
請指教。
謝謝
請用您正在開發的語言標記問題 - 您將得到更好的答案 – codebox
您正在使用哪種語言? –
C#語言。 。 。 – Harsha