具有 class 属性的 C# 记录,它们如何工作?

C# records having class properties, how do they work?

我阅读了很多关于记录和 C# 9 和 10 中的新特性的文章。我知道记录是引用类型,具有一些平等的魔力,因此它们应该表现得像值类型。我现在喜欢将 record 用于具有简单属性的模型。

这样的模型怎么样:

public record MyRecord
{
    public Dictionary<string, string> MyDictionary { get; init; } = new Dictionary<string, string>();
}

我不确定当 属性 之一是 class(字典)时使用 record 是否有好处。我想尽可能多地了解在记录中使用 class 属性的具体情况、影响等。

来自C# Documentation and the Specification for record:

For record types, including record struct and readonly record struct, two objects are equal if they are of the same type and store the same values.

The record type implements System.IEquatable<R> and includes a synthesized strongly-typed overload of Equals(R? other) where R is the record type.

...

The synthesized Equals(R?) returns true if and only if each of the following are true:

  • other is not null, and
  • For each instance field fieldN in the record type that is not inherited, the value of
    System.Collections.Generic.EqualityComparer<TN>.Default.Equals(fieldN, other.fieldN) where TN is the field type, and
  • If there is a base record type, the value of base.Equals(other) (a non-virtual call to public virtual bool Equals(Base? other));
    otherwise the value of EqualityContract == other.EqualityContract.

由于默认情况下字典的“相等”定义是引用相等,当且仅当它们引用 same 字典时,您的两条记录才“相等”。没有内置机制来确保字典包含相同的键和值(这似乎是您想要的)。