【C#】重写HashCode,去重相同坐标的二维点

时间:2024-11-03 12:05:33
  1. 创建Point类,重写GetHashCodeEquals函数。
    这样相同XY坐标的Point对象会返回相同的HashCode,就可以使用HashSet集合对点坐标去重。
        class Point
        {
            public double X;
            public double Y;
            public Point(double x, double y)
            {
                X = x; Y = y;
            }
            public sealed override int GetHashCode()
            {
                int result = 17;
                result = 37 * result + X.GetHashCode();
                result = 37 * result + Y.GetHashCode();
                return result;
            }
            public sealed override bool Equals(object obj)
            {
                if(obj is Point pt)
                {
                    return X == pt.X && Y == pt.Y;
                }
                return false;
            }
            public sealed override string ToString()
            {
                return $"X={X},Y={Y}";
            }
        }
  1. 使用HashSet集合处理所有点坐标。
        public void TestMethod1()
        {
            var hashSet = new HashSet<Point>();
            hashSet.Add(new Point(0,0));
            hashSet.Add(new Point(0.1,1.1));
            hashSet.Add(new Point(0.1,1.1));//返回false
            hashSet.Add(new Point(0.1,2));
            hashSet.Add(new Point(0.1,2));//返回false

            foreach(Point pt in hashSet)
            {
                Console.WriteLine(pt.ToString());
            }
        }

输出结果:

X = 0,Y = 0
X = 0.1,Y = 1.1
X = 0.1,Y = 2

如果Point类中不重写GetHashCodeEquals函数,那么上面会输出:

X=0,Y=0
X=0.1,Y=1.1
X=0.1,Y=1.1
X=0.1,Y=2
X=0.1,Y=2