我需要比较两个List<Car>
数据的相等性。
我用谷歌搜索并找到了合适的方法SequenceEqual
看来我所做的一切都是MSDN上的
但如果类中Car
存在对象Radio
,则比较失败。
我的课程:
public class Car : IEquatable<Car>
{
public string? Model { get; set; }
public bool Dead { get; set; }
public int MaxSpeed { get; set; }
public Radio? Music { get; set; }
public bool Equals(Car? other)
{
if (other == null)
return false;
return Model == other.Model &&
Dead == other.Dead &&
MaxSpeed == other.MaxSpeed &&
Music == other.Music;
}
public override bool Equals(object? obj) => Equals(obj as Car);
public override int GetHashCode() => (Model, Dead, MaxSpeed, Music).GetHashCode();
}
public class Radio : IEquatable<Radio>
{
public int Volume { get; set; }
public bool Equals(Radio? other)
{
if (other == null)
{
return false;
}
return Volume == other.Volume;
}
public override bool Equals(object? obj) => Equals(obj as Radio);
public override int GetHashCode() => (Volume).GetHashCode();
}
未通过测试
[TestMethod]
public void CarTest_Equal_True()
{
// Arrange
List<Car> cars1 = new()
{
new Car()
{
Dead = false,
MaxSpeed = 100,
Model = "Tesla",
Music = new Radio()
{
Volume = 100
}
}
};
List<Car> cars2 = new()
{
new Car()
{
Dead = false,
MaxSpeed = 100,
Model = "Tesla",
Music = new Radio()
{
Volume = 100
}
}
};
// Act
bool equal = cars1.SequenceEqual(cars2);
// Assert
Assert.AreEqual(true, equal);
}
通过测试
[TestMethod]
public void CarTest_MusicNull_Equal_True()
{
// Arrange
List<Car> cars1 = new()
{
new Car()
{
Dead = false,
MaxSpeed = 100,
Model = "Tesla"
}
};
List<Car> cars2 = new()
{
new Car()
{
Dead = false,
MaxSpeed = 100,
Model = "Tesla"
}
};
// Act
bool equal = cars1.SequenceEqual(cars2);
// Assert
Assert.AreEqual(true, equal);
}
错误就出在这里:
你需要写:
在原著中,虽然内容是相同的,但对象是不同的。替换通过对象的内容来比较对象。