相关疑难解决方法(0)

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

测试新的 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)
    { …
Run Code Online (Sandbox Code Playgroud)

c# c#-9.0 c#-record-type

7
推荐指数
0
解决办法
3441
查看次数

标签 统计

c# ×1

c#-9.0 ×1

c#-record-type ×1