我有一个名为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'因此,我如何表达返回,使它返回一个int而不是bool,因为它现在正在这样做?
更新
如果我将返回代码更改为:
return this.coordinate.CompareTo(other.coordinate);我得到以下错误信息:
错误1 'ShapeD.Game_Objects.Shape‘不能实现接口成员ShapeD.Game_Objects.Shape'ShapeD.Game_Objects.Shape.CompareTo(ShapeD.Game_Objects.Shape)‘无法实现'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)’,因为它没有匹配的返回类型'int‘。C:\Usmaan\Documents\Visual 2012\Projects\ ShapeD \ Objects\Shape.cs 10 18 ShapeD
发布于 2013-08-06 06:02:59
IComparable意味着,在某种意义上可以比较两个对象,您可以判断哪个对象具有“更高的值”。它通常用于排序目的。您应该重写Equals方法,而.You也应该使用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()
}
}发布于 2013-08-06 06:06:00
因为您只想检查是否相等,所以请实现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
}注意事项
应该为可能存储在IEquatable集合中的任何对象实现,您还必须重写对象的Equals method.Also,正如在其他ans中指出的,使用点结构而不是多维数组
发布于 2013-08-06 05:52:27
为了执行包含检查,您需要覆盖Shape类中的等于运算符。
https://stackoverflow.com/questions/18072425
复制相似问题