2013-08-06 8 views
6

public int[,] coordinate { get; set; }フィールドを含むShapeというオブジェクトがあります。C#のIComparable

私は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を返すように戻り値を返すようにするにはどうすればよいですか?

UPDATE

私はリターン・コードを変更する場合:

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

私は、次のようなエラーメッセージを指定を取得します:実行するための

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 other)** to ** public int CompareTo(オブジェクト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はそれを使って単純に1点のx座標とy座標を設定していたので、私はそれを 'Point'構造体に置き換えました。私は 'ReferenceEquals'の使用に関する問題も見ていません。何か不足していますか? –

2

はあなたをチェック入ってオーバーライドする必要がオペレーターを等しいですシェイプクラスで

3

だけ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 

} 

NOTE

IEquatableあなたはまた、オブジェクトのEquals method.Alsoを無効にする必要がありますgenericコレクション他に格納される可能性があります任意のオブジェクトのために実装する必要があります他のansで指摘されているようにPoint multimentional配列の代わりに構造体

関連する問題