测试新的 C# 9 记录,并希望澄清为什么序列相等在记录上不起作用?
假设我有以下代码:
public record Person(string FirstName, string LastName);
以下代码将返回 true 表示相等(这里没什么奇怪的):
var first = new Person("Bruce", "Wayne");
var second = new Person("Bruce", "Wayne");
var result = first == second; // Returns true
但是,如果我创建以下记录:
public record Basket(string[] Items);
我做了一个类似的测试:
var first = new Basket(new[] { "Banana", "Apple" });
var second = new Basket(new[] { "Banana", "Apple" });
var result = first == second;
结果将返回 false。这可以通过定义自己的 Equals 方法来解决:
public record Basket(string[] Items)
{
public virtual bool Equals(Basket other)
{
return Items.SequenceEqual(other.Items);
}
public override int GetHashCode() => Items.GetHashCode();
}
但我很好奇这背后的决定(如果有的话)。