gpt4 book ai didi

c# - 如何在 C# 9 中复制/克隆记录?

转载 作者:行者123 更新时间:2023-12-03 14:40:19 25 4
gpt4 key购买 nike

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

A record type contains two copying members:

A constructor taking a single argument of the record type. It isreferred to as a "copy constructor". A synthesized publicparameterless 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 { };
但是克隆呢?根据上述规范,克隆方法是公开的。但它的名字是什么?或者它是一个有效的随机字符串,因此不应该在记录的继承层次结构之外调用它?如果是这样,深拷贝记录的正确方法是什么?从规范看来,一个人能够创建自己的克隆方法。是这样吗?它应该如何工作的一个例子是什么?

最佳答案

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 中。

关于c# - 如何在 C# 9 中复制/克隆记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63994473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com