简体   繁体   中英

How to properly compare 2 objects from the same class?

I have the following class dto:

public class Field
{
    public bool isEmptyField { get; set; }
    public bool isPawn { get; set; }
    public bool isDame { get; set; }
    public string color { get; set; }


    public Field(bool isEmptyField, bool isPawn, bool isDame, string color)
    {
        this.isEmptyField = isEmptyField;
        this.isPawn = isPawn;
        this.isDame = isDame;
        this.color = color;
    }
}

Can someone tell me why i can't compare objects from this class when i am using Equals() or == ?

Example:

Condition

if (TypeOfGame.gameBoard[indexFrom].Equals(Constant.PAWN_RED))

在此处输入图像描述

在此处输入图像描述

Result with Equals()
在此处输入图像描述

Result with == 在此处输入图像描述

Can someone explain this please? I am newbie with C# i really dont know what is going on here...

You need to implement Equals method of Object that does nothing else comparing references.

https://referencesource.microsoft.com/#mscorlib/system/object.cs,f2a579c50b414717,references

public class Field : IEquatable<Field>
{
  public bool isEmptyField { get; set; }
  public bool isPawn { get; set; }
  public bool isDame { get; set; }
  public string color { get; set; }

  public Field(bool isEmptyField, bool isPawn, bool isDame, string color)
  {
    this.isEmptyField = isEmptyField;
    this.isPawn = isPawn;
    this.isDame = isDame;
    this.color = color;
  }

  public override bool Equals(object obj)
  {
    return Equals(this, obj as Field);
  }

  public bool Equals(Field obj)
  {
    return Equals(this, obj);
  }

  static public bool Equals(Field x, Field y)
  {
    return ( ReferenceEquals(x, null) && ReferenceEquals(y, null) )
        || (    !ReferenceEquals(x, null)
             && !ReferenceEquals(y, null)
             && ( x.isEmptyField == y.isEmptyField )
             && ( x.isPawn == y.isPawn )
             && ( x.isDame == y.isDame )
             && ( x.color == y.color ) );
  }
}

IEquatable<Field> is not needed but can be usefull and it doesn't cost much.

Test

var field1 = new Field(true, true, true, "test");
var field2 = new Field(true, true, true, "test");
var field3 = new Field(false, true, true, "test");
var field4 = new Field(true, true, true, "test2");

Console.WriteLine(field1.Equals(field2));
Console.WriteLine(field1.Equals(field3));
Console.WriteLine(field1.Equals(field4));
Console.WriteLine(field1.Equals(null));
Console.WriteLine(Field.Equals(null, null));

Output

True
False
False
False
True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM