标签:tostring get hashcode inf 差值 范围 info value img
先看效果
实现方法
新建一个Point类
1 class Point 2 { 3 4 public double X; 5 public double Y; 6 public double Z; 7 public Point(double x, double y, double z) 8 { 9 this.X = x; 10 this.Y = y; 11 this.Z = z; 12 } 13 }
新建一个比较器类 实现IEqualityComparer<Point>接口
1 class PointCompare : IEqualityComparer<Point> 2 { 3 private double _tolerance = 0.1; 4 public double Tolerance { get => _tolerance; set => _tolerance = value; } 5 6 //判定点的容差值是否在范围内 7 public bool Equals(Point x, Point y) 8 { 9 return (Math.Abs(x.X - y.X) <= _tolerance && Math.Abs(x.Y - y.Y) <= _tolerance && Math.Abs(x.Z - y.Z) <= _tolerance); 10 } 11 12 //由于直接获取对象的HashCode,用HashCode进行比较的速度比 Equals 方法更快, 13 //因此IEqualityComparer内部会在使用 Equals 前先使用 GetHashCode 方法,在两个对象的HashCode都相同时即刻判断对象相等。 14 //而当两个对象HashCode相同时, Equals 方法就会被调用,对要比较的对象进行判断。 15 //由于在上例中list中的两个引用实际上是两个不同的对象,因此HashCode必定不相同 需要改写 GetHashCode方法 16 public int GetHashCode([DisallowNull] Point obj) 17 { 18 return 0; 19 //return obj.ToString().GetHashCode();这里这么写也可以,暂时不知道为啥 20 } 21 }
运行测试
1 static void Main(string[] args) 2 { 3 4 var list = new List<Point> 5 { 6 new Point(0,0,0), 7 new Point(2,2,2), 8 new Point(5,5,5), 9 new Point(6,6,6), 10 new Point(10,10,10), 11 new Point(20,20,20) 12 }; 13 14 list.ForEach(i => Console.WriteLine($"Point:{i.X},{i.Y},{i.Z}")); 15 16 var comparer = new PointCompare() { Tolerance = 6 }; 17 18 list = list.Distinct(comparer).ToList(); 19 20 21 22 Console.WriteLine("\n去重后"); 23 list.ForEach(i => Console.WriteLine($"Point:{i.X},{i.Y},{i.Z}")); 24 }
标签:tostring get hashcode inf 差值 范围 info value img
原文地址:https://www.cnblogs.com/AtTheMoment/p/14728846.html