开发者

How to check if 2 variables in a class is equal?

I've tried to check if 2 variables in a class, or if 2 classes are equal, but my messagebox still doesn't show.

Maptiles : this is a list, with classes, and each class has variables: ID, X and Y

Mapindex : this is the variable to loop through all classes in maptiles list.

Mapnumber: this variable starts on 1, I use it to check on all classes

Here's code:

            for (int mapIndex = 0; mapIndex < MapTiles.Count; mapIndex++)
            {
                if (mapIndex + mapNumber >= MapTiles.Count)
                {
                    break;
                }
                if(MapTiles[mapIndex].Equals(MapTiles[mapIndex+mapNumber])) 
                {
                    System.Windows.Forms.MessageBox.Show("REMOVE");
                }
             开发者_JAVA百科   mapNumber++;
            }

So question is, how to make it show, or how to check if 2 classes are the same?? Thanx.


Your class needs to override Object.Equals() at least for that comparison to work out. Also implementing IEquatable is a good idea.

More information: Guidelines for Overloading Equals() and Operator == (C# Programming Guide)


You will need to override the equals operator. See http://msdn.microsoft.com/en-us/library/ms173147.aspx


I think is more natural way in .NET is override Equals() and just compare objects inside that method.

You can implement whatever comparison complexity you want, it's important to structure in ".NET expected way", so someone after 2 years will able understan at least a logic of a stuff.

Regards.


You can as others have said can override Equals (and also GetHashCode).

However if you don't want to do this or can't do that you can write a class that implements IEqualityComparer.

Although implementing IEqualityComparer is not required (you could just write a method that did the comparision) it would prove useful if you decided to go use a Linq expression like Distinct on a collection

For example

class YourImplementedComparer: IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.X== y.X &&
            x.Y == y.Y &&
            x.Y == y.Y
    }

    public int GetHashCode(Item obj) {
        return obj.X.GetHashCode() ^
            obj.Y.GetHashCode() ^
            obj.ID.GetHashCode() ;
    }
}

then using it with distinct

MapTiles  =  MapTiles.Distinct(new YourImplementedComparer)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜