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

如何解决如何在C#9中复制/克隆记录?

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

记录类型包含两个复制成员:

使用记录类型的单个参数的构造函数。它是 称为“复制构造函数”。综合公众 具有编译器保留名称的无参数实例“克隆”方法

但是我似乎无法称呼这两个复制成员中的一个:

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 { };

但是克隆呢?根据上面的说明,克隆方法是公开的。但是它叫什么名字呢?还是它是一个有效的随机字符串,因此不应在记录的继承层次结构之外调用它?如果是这样,深度复制记录的正确方法是什么?从规范看来,一个人能够创建自己的克隆方法。是这样吗,它将是如何工作的一个例子?

解决方法

但是克隆呢?

var r4 = r with { };

在r上执行浅表克隆。

根据上述规范,克隆方法是公共的。但是它叫什么名字?

C#编译器有一个相当普遍的技巧,它可以为生成的成员提供在C#中非法但在IL中合法的成员名称,因此,即使它们是公共的,也只能从编译器中调用它们。在这种情况下,Clone方法的名称为<Clone>$

如果是这样,深度复制记录的正确方法是什么?

深复制使您不走运。但是,由于记录在理想情况下应该是不变的,因此,浅表副本,深表副本和原始实例在实践上应该没有区别。

从规范看来,一个人可以创建自己的克隆方法。是这样吗,它将是如何工作的一个例子?

不幸的是,这并没有降到C#9,但是很有可能会出现在C#10中。

,

关于记录的克隆,是的,看来/* REF https://stackoverflow.com/a/49575979 */ /* REF https://stackoverflow.com/questions/26607330/css-display-none-and-opacity-animation-with-keyframes-not-working/64857102#64857102 */ body,html { /* eye candy */ background: #444; display: flex; min-height: 100vh; align-items: center; justify-content: center; } button { font-size: 4em; border-radius: 20px; margin-left: 60px;} div { /* eye candy */ width: 200px; height: 100px; border-radius: 20px; background: green; display: flex; align-items: center; justify-content: center; font-family: sans-serif; font-size: 2em; color: white; text-align: center; text-shadow: 0px 2px 4px rgba(0,.6); } /* using this extra .active class prevents that there is an animation already on loading */ .active { animation: fadeAndHideBack 1s linear forwards; } .play { opacity: 0; /* learning curve: setting background "awaits" animation finish,setting scale prematurely jumps to it,then doing animation from there */ animation: fadeAndHide 1s linear forwards; } @keyframes fadeAndHide { 0% { opacity: 1; } 99.9% { opacity: 0; max-height: 100px; } 100% { opacity: 0; max-height: 0; } } @keyframes fadeAndHideBack { 0% { opacity: 0; max-height: 0; } 0.1% { opacity: 0; max-height: 100px; } 100% { opacity: 1; } }将为您创建一个深层克隆,如下例所示:

记录示例:

<div class="target"></div>
<button onclick="toggleTarget()">
  Toggle
</button>

输出:

with

此外,如我们所见,如果我们明确声明了记录属性,那么我们还可以更改记录属性的开箱即用的不变性。我们也可以编写自己的构造函数。

如果我们对一个普通的类进行上述操作,则副本将是预期的浅表克隆。

课程示例:

using System;
                    
public class Program
{
    public static void Main()
    {
        var person1 = new Person
        {
            Hair = "brown",Skin = "tawny"
        };
        
        var inhabitant1 = new Inhabitant
        {
            Name = "Moreno",Profile = person1
        };
        var inhabitant2 = new Inhabitant
        {
            Name = "Branquinho",Profile = inhabitant1.Profile with { Skin = "sparkle" }
        };
        
        Console.WriteLine("--- Brown,Tawny ---");
        Console.WriteLine(inhabitant1.ToString());
        Console.WriteLine(inhabitant2.ToString());
        
        inhabitant1.Profile.Hair = "painted";
        
        Console.WriteLine("\n--- Painted,Tawny ---");
        Console.WriteLine(inhabitant1.ToString());
        Console.WriteLine(inhabitant2.ToString());
        
        inhabitant2.Profile.Skin = "sunburn";
        
        Console.WriteLine("\n--- Painted,Tawny ---");
        Console.WriteLine(inhabitant1.ToString());
        Console.WriteLine(inhabitant2.ToString());
        
        person1.Skin = "green";
        person1.Hair = "green";
        
        Console.WriteLine("\n--- Green,Green ---");
        Console.WriteLine(inhabitant1.ToString());
        Console.WriteLine(inhabitant2.ToString());
        
        inhabitant1.Profile = new Person
        {
            Skin = "blue",Hair = "blue"
        };
        
        Console.WriteLine("\n--- Blue,Blue ---");
        Console.WriteLine(inhabitant1.ToString());
        Console.WriteLine(inhabitant2.ToString());
        
        
    }
    
    public record Inhabitant()
    {
        public string Name { get; set; }
        public Person Profile { get; set; }
    }
    
    public record Person()
    {
        public string Hair { get; set; }
        public string Skin { get; set; }
    }
}

输出:

--- Brown,Tawny ---
Inhabitant { Name = Moreno,Profile = Person { Hair = brown,Skin = tawny } }
Inhabitant { Name = Branquinho,Skin = sparkle } }

--- Painted,Profile = Person { Hair = painted,Skin = sunburn } }

--- Green,Green ---
Inhabitant { Name = Moreno,Profile = Person { Hair = green,Skin = green } }
Inhabitant { Name = Branquinho,Skin = sunburn } }

--- Blue,Blue ---
Inhabitant { Name = Moreno,Profile = Person { Hair = blue,Skin = blue } }
Inhabitant { Name = Branquinho,Skin = sunburn } }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-