2013-08-06 24 views
6

我有一個叫做Shape的對象,其中包含一個public int[,] coordinate { get; set; }字段。C在C中可以比較#

我有一個單獨的類,其中有一個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,因爲此刻它正在這樣做?

UPDATE

如果我改變返回代碼:

return this.coordinate.CompareTo(other.coordinate); 

我收到以下錯誤mesage:

Error 1 'ShapeD.Game_Objects.Shape' does not implement interface member 'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)'. 'ShapeD.Game_Objects.Shape.CompareTo(ShapeD.Game_Objects.Shape)' cannot implement 'System.IComparable.CompareTo(ShapeD.Game_Objects.Shape)' because it does not have the matching return type of 'int'. C:\Users\Usmaan\Documents\Visual Studio 2012\Projects\ShapeD\ShapeD\ShapeD\Game Objects\Shape.cs 10 18 ShapeD

+0

新的錯誤信息是公平的簡單來解決,更改** public int CompareTo(Shape其他)** to ** public int CompareTo(object other)**但是然後您將面臨投射問題並且CompareTo對於多維數組不存在。 –

回答

3

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.X^coordinate.Y; 
    } 
} 
+0

當然啊。非常感謝你解釋! – Subby

+0

@Subby @Nikita這些'Equals'和'GetHashCode'實現看起來不對。你的座標是一個多元數組,你可能不希望你的平等基於'ReferenceEquals'。 –

+0

@ErenErsönmez,在我的例子中沒有多維數組。在我看來,OP使用它來簡單地設置單點的x和y座標,所以我用'Point'結構替換了它。我也沒有看到使用'ReferenceEquals'的問題。我錯過了什麼嗎? –

2

執行包含檢查你需要重寫等於運算符在Shape類中。

3

既然你只需要檢查平等實現IEquatable接口IComparableIComparable用於排序目的

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應該對可能被存儲在一個generic收集其他你就必須也覆蓋對象的Equals method.Also任何物體來實現正如其他答案中指出的那樣,使用Point結構代替多維數組