You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中深拷贝含私有只读字段的Patient结构体并重置Random实例

解决方案

完全可行,核心思路是利用结构体的Clone方法可访问私有只读字段_seed的特性,通过调用带参数的构造函数重新初始化Crn,同时完成PatientCovariates的深拷贝。

修改后的关键代码

internal struct Patient : ICloneable
{
    private readonly int _seed;
    public readonly Random Crn { get; }
    public Dictionary<int, Dictionary<string, string>> PatientCovariates { get; set; }

    public Patient(int seed)
    {
        _seed = seed;
        Crn = new Random(_seed);
        PatientCovariates = new();
    }

    public readonly object Clone()
    {
        // 用当前实例的_seed调用构造函数,重新生成相同初始状态的Crn
        var clonedPatient = new Patient(_seed);
        // 深拷贝PatientCovariates的层级结构
        clonedPatient.PatientCovariates = this.PatientCovariates.ToDictionary(
            entry => entry.Key,
            entry => entry.Value.ToDictionary(
                innerEntry => innerEntry.Key,
                innerEntry => innerEntry.Value
            )
        );
        return clonedPatient;
    }
}

关键点说明

  • 保持字段状态:_seed依然是私有只读,Crn依然是只读属性,完全符合你的要求。
  • Random一致性:通过传入原实例的_seed调用构造函数,新的Crn实例会和原对象的Crn拥有完全相同的随机序列起点。
  • 深拷贝有效性:嵌套的ToDictionary调用确保了PatientCovariates的每一层字典都是独立拷贝,修改克隆对象的协变量不会影响原对象。

验证效果

在你的DoStuff方法中,克隆后的patObjCopy和patObjCopyTwo的Crn会生成完全相同的随机数,同时它们的PatientCovariates是独立的,修改克隆对象的协变量不会改动_baselinePatients中的原数据。

内容的提问来源于stack exchange,提问作者KGB91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 08:42:04