C#自定义类的相等判断
引言
在项目中,使用了自定义的类RegionRect来记录区域的四个边界,以为RegionRect的相等判断是其内的字段数值判断,但对于自定义类的相等判断是引用判断,需要在自定义类中重写Equals和GetHashCode。
代码如下
public class RegionRect
{
public int minX;
public int maxX;
public int minY;
public int maxY;
public RegionRect(int _minX, int _minY, int _maxX, int _maxY)
{
minX = _minX;
maxX = _maxX;
minY = _minY;
maxY = _maxY;
}
public bool Equals(RegionRect other) =>
other != null && minX == other.minX && minY == other.minY && maxX == other.maxX && maxY == other.maxY;
public override bool Equals(object obj) => Equals(obj as RegionRect);
public override int GetHashCode() => HashCode.Combine(minX, minY, maxX, maxY);
public static bool operator ==(RegionRect a, RegionRect b) => Equals(a, b);
public static bool operator !=(RegionRect a, RegionRect b) => !Equals(a, b);
}
小结
在需要进行相等判断时,直接使用库中满足需求的类,比如此例使用Rect就好了(做个减法得到Rect中的width和height),可以避免重写方法。

浙公网安备 33010602011771号