在 C# 中比较两个 class 对象

Compare two class objects in C#

我试图在我的单元测试中比较两个 class 对象,但即使字段相同,也会出现异常。

[TestMethod]
public async Task getResult()
{
var expectedResult = new List<myClass>(){
    new myClass(){
        Id = 1
        Name = "updatedName"
    }
}
// here I am calling POST method to update the name
// won't include the full code because of brevity

// now getting the result
var actualResult = await this.getResult(1) // getting the result of the above Id

Assert.Equal(expectedResult, actualResult)
}

我得到异常:

myClass
{
    Id = 1
    Name = "updatedName"
} because myClass should match, but found
myClass
{
    Id = 1
    Name = "updatedName"
} 

我很困惑,因为所有字段都是相同的,为什么它们不匹配?

Assert.Equal 依赖对象的 .Equals 方法 (see here)。创建您自己的 classes 时,您可以选择 覆盖 此方法并添加您自己的比较两个对象相等性的逻辑(例如,逐个字段相等性检查)。

如果不重写,有一个默认的.Equals继承自Object,相当于.ReferenceEquals:如果两个对象returns为真具有相同的 reference,否则为 false。两个对象具有相同引用的唯一情况是 相同 对象。

在您的情况下,您可以为 class (e.g., see here) or you can try to follow some of the advice given in this SO answer on how to perform deep equality checking of two objects. Third option is to create a separate class inherited from IEqualityComparer, which will purely provide the equality checking logic for your object while not being a part of your class codebase (for example, see this article) 定义 .Equals 覆盖。