记录在可枚举相等性上返回 false

Hay*_*den 7 c# c#-9.0 c#-record-type

测试新的 C# 9 记录,并希望澄清为什么序列相等在记录上不起作用?

假设我有以下代码:

public record Person(string FirstName, string LastName);
Run Code Online (Sandbox Code Playgroud)

以下代码将返回 true 表示相等(这里没什么奇怪的):

var first = new Person("Bruce", "Wayne");
var second = new Person("Bruce", "Wayne");
var result = first == second; // Returns true
Run Code Online (Sandbox Code Playgroud)

但是,如果我创建以下记录:

public record Basket(string[] Items);
Run Code Online (Sandbox Code Playgroud)

我做了一个类似的测试:

var first = new Basket(new[] { "Banana", "Apple" });
var second = new Basket(new[] { "Banana", "Apple" });
var result = first == second;
Run Code Online (Sandbox Code Playgroud)

结果将返回 false。这可以通过定义自己的 Equals 方法来解决:

public record Basket(string[] Items)
{
    public virtual bool Equals(Basket other)
    {
        return Items.SequenceEqual(other.Items);
    }

    public override int GetHashCode() => Items.GetHashCode();
}
Run Code Online (Sandbox Code Playgroud)

但我很好奇这背后的决定(如果有的话)。