IC#中的可比较性
本文关键字:可比较 IC# | 更新日期: 2023-09-27 18:26:30
我有一个名为Shape
的对象,它包含一个public int[,] coordinate { get; set; }
字段。
我有一个单独的类,它有一个Shape
对象的集合。在某一点上,我想检查一下:
if(shapes.Contains(shape))
{
// DoSomething
}
因此,在Shape
类中,我添加了IComparable
引用并插入了CompareTo
方法:
public int CompareTo(Shape other)
{
return this.coordinate.Equals(other.coordinate);
}
然而,我得到了一个错误:
Cannot implicitly convert type 'bool' to 'int'
因此,我如何表达return,使其返回int,而不是像现在这样返回bool?
更新
如果我将返回代码更改为:
return this.coordinate.CompareTo(other.coordinate);
我得到以下错误台面:
错误1"ShapeD.Game_Objects.Shape"未实现接口成员"System.IComparable.CompareTo(ShapeD.Game _Objects.Shape)"。"ShapeD.Game _Objects.chape.CompareTo(ShapeD.Game _Oobjects.Shape)"无法实现"System.ICcomparable.CompleteTo(ShapeD.Game_Objects.Shape)",因为它没有匹配的返回类型"int"。C: ''Users''Usmaan''Documents''Visual Studio 2012''Projects''ShapeD''ShapeD''游戏对象''Shape.cs 10 18 ShapeD
IComparable暗示,两个对象可以在某种意义上进行比较,你可以判断哪个对象有"更高的值";。它通常用于排序目的。您应该重写Equals
方法。您还应该使用Point结构而不是数组。
class Shape : IEquatable<Shape>
{
public Point coordinate { get; set; }
public bool Equals(Shape other)
{
if (other == null) return false;
return coordinate.Equals(other.coordinate);
}
public override bool Equals(object other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
var shape = other as Shape;
return Equals(shape);
}
public override int GetHashCode()
{
return coordinate.GetHashCode()
}
}
因为您只想检查相等性,所以实现IEquatable接口而不是IComparable
。IComparable
用于分拣
public bool Equals(Shape s)
{
int count=0;
int[] temp1=new int[this.coordinate.Length];
foreach(int x in this.coordinate)temp1[count++]=x;//convert to single dimention
count=0;
int[] temp2=new int[s.coordinate.Length];
foreach(int x in s.coordinate)temp2[count++]=x;//convert to single dimention
return temp1.SequenceEqual(temp2);//check if they are equal
}
注意
应该为可能存储在generic
集合中的任何对象实现IEquatable
,否则您还必须重写object的Equals
方法。也正如在其他ans中指出的那样,使用Point结构而不是多维数组
要执行Contains检查,需要覆盖Shape类中的Equals运算符。
重新提出一个旧问题,只是因为尽管答案很差,它仍然会在谷歌上引起点击。您不应该使用CompareTo或Equals。这两者都不符合你想要做的事情,只会引起混乱,这里写的答案就是明证。编写自己的方法,称为IntersectsWith。看看任何像样的几何库(例如,如果你很乐意从c++中提取,请使用boost),了解如何做到这一点。至于从bool到int的强制转换,可以通过将bool与?三元运算符。