如何在 C# 9 中 copy/clone 记录?

How to copy/clone records in C# 9?

C# 9 records feature specification包括以下内容:

A record type contains two copying members:

A constructor taking a single argument of the record type. It is referred to as a "copy constructor". A synthesized public parameterless instance "clone" method with a compiler-reserved name

但我似乎无法调用这两个复制成员中的任何一个:

public record R(int A);
// ...
var r2 = new R(r); // ERROR: inaccessible due to protection level
var r3 = r.Clone(); // ERROR: R does not contain a definition for Clone

据此,我了解到构造函数是受保护的,因此无法在记录的继承层次结构之外访问。所以我们留下了这样的代码:

var r4 = r with { };

但是克隆呢?根据上面的规范,克隆方法是public。但是它的名字是什么?或者它是一个有效的随机字符串,因此不应在记录的继承层次结构之外调用它?如果是这样,深拷贝记录的正确方法是什么?从规范来看,似乎可以创建自己的克隆方法。是这样吗,它应该如何工作的例子是什么?

But what about cloning?

var r4 = r with { };

在 r 上执行浅克隆。

The clone method is public according to the specification above. But what is its name?

C# 编译器有一个相当常见的技巧,它会为生成的成员命名,这些名称在 C# 中是非法的,但在 IL 中是合法的,因此除了编译器之外不能调用它们,即使它们是 public。在这种情况下,Clone 方法的名称是 <Clone>$.

If so, what is the correct way to deep copy records?

深度复制你倒霉了。然而,由于理想情况下记录应该是不可变的,因此浅拷贝、深拷贝和原始实例之间在实践中应该没有区别。

It seems from the specification that one is able to create one's own clone method. Is this so, and what would be an example of how it should work?

遗憾的是,这没有在 C# 9 中实现,但很有可能在 C# 10 中实现。