c# - 为什么 IndexOf 有时不适用于记录列表(或集合)?

标签 c# c#-9.0

使用 C# 9.0 功能记录时,我遇到了记录列表(或集合)的 IndexOf 方法有时似乎不起作用的问题。

这发生在以下示例中。 IndexOf(b) 返回 0,但我错误地预期为 1:

void Main()
{
    var a = new Thing("Hello", 100);
    var b = new Thing("Hello", 100);
    
    var things = new List<Thing> { a, b };
    
    Console.WriteLine(things.IndexOf(b));
}

public record Thing (string Name, int Number);

所以我的问题是,为什么会发生这种情况以及如何解决这个问题?

最佳答案

从此question我了解到 IndexOf 方法使用 Equals 方法来查找其匹配项。

在此article我了解到记录取决于值(value)平等:

For records, value equality means that two variables of a record type are equal if the types match and all property and field values match.

因此,我在示例中得到了意外的索引,因为我希望记录依赖于引用相等性,例如类。但如果变量 a 与 b 具有相同的类型和值,则 IndexOf(b) 返回 a 的索引,而不是 b。

可能的解决方案

  1. 按照讨论的方式为记录编写自定义相等性检查 here .
  2. 首先问问自己,类列表是否更合适。
  3. 重构您的逻辑,使其基于与 ReferenceEquals 的比较

关于c# - 为什么 IndexOf 有时不适用于记录列表(或集合)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77200456/

相关文章:

c# - Asp .net Core 使用服务实例调用在 Startup.cs 中运行的另一个方法中的方法

c# - 从 Azure blob 读取 Parquet 文件,无需将其下载到本地 c# .net

c# 9.0 记录 - 反射和通用约束

c# - 我可以让 Json.net 使用 "primary"构造函数反序列化 C# 9 记录类型,就好像它有 [JsonConstructor] 一样?

c# - Angular Web Api 2 不适用于 POST : 405 Method Not Allowed

c# - 密码保护数据库

c# - 带有 COM 互操作的 Resharper 提示 "Cannot access internal constructor"

c# - C#9 不支持 JsonPropertyNameAttribute 记录?

c# - 记录 'Lenses' - with 表达式的表达式树

c#-9.0 - 在 C# 9.0 中的 switch-case 中更新多个变量