c# - 如何正确比较同一类的 2 个对象?

标签 c#

我有以下类 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;
    }
}

有人能告诉我为什么在使用 Equals()== 时无法比较此类中的对象吗?

示例:

条件

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

enter image description here

enter image description here

结果为 Equals()
enter image description here

== 的结果 enter image description here

有人可以解释一下吗?我是 C# 的新手,我真的不知道这里发生了什么......

最佳答案

您需要实现 Equals Object的方法|比较引用什么都不做。

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>不需要,但很有用,而且成本不高。

测试

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));

输出

True
False
False
False
True

关于c# - 如何正确比较同一类的 2 个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62855111/

相关文章:

c# - Amazon S3 TransferUtility.Upload 在 C# 中挂起

c# - 如何使用上一次调用的数据进行第二次 JS .post 调用?

c# - 需要解析一个xml字符串

c# - 在桌面上拖动 WPF 窗体

c# - 自定义 OutputCache 提供程序在 Add() 和 Set() 上生成不同的键

c# - "NullReferenceException"尝试设置 DataGridView 列宽时,否则会正常显示数据

c# - 如何从 MySQL 获取所有可用数据库到 C# Windows 窗体中的组合框控件

C# Linq to XML,当 child 满足条件时获取 parent

C# 银行示例 - 客户类 - 取款、存款等

c# - WCF(或替代方案)在 Internet 上的机器上设置 Controller-worker