Ich versuche zu machen Eine tiefe Kopie eines Objekts, Patient , in einem gleichzeitigen Dokument , _baselinePatients , zu einem anderen gleichzeitigen Dokument , _patientsCurrentarm in C#, fehlschlägt aber. Es scheint, als ob der Patient, den ich von _BaselinePatients kopieren kann, zu _PatientsCurrentarm nur ein Zeiger ist Es hat mit der Tatsache zu tun, dass die beiden gleichzeitigen Verantwortlichkeiten _baselinepatients und zu tun haben _patientsCurrentarm Enthält die gleichen Datentypen? bereits hinzugefügt. Schlüssel: Kovariate '
Code: Select all
using System.Collections.Concurrent;
namespace ExampleCode;
internal class Program
{
private static void Main(string[] args)
{
Exampel obj = new();
obj.DoStuff();
}
}
internal class Exampel()
{
///
/// For the baseline patients (patient ID, patient object), same for all arms and only generated once
///
private ConcurrentDictionary _baselinePatients = new();
///
/// Patients in the current arm (patient ID, patient object)
///
private ConcurrentDictionary _patientsCurrentArm = new();
public void DoStuff()
{
const int EXAMPLE_CYCLE = 0;
// Set the number of arms and patients
int _nArms = 2;
int _nPatients = 5;
// Add patients at baseline to _baselinePatients
for (int i = 0; i < _nPatients; i++) {
Patient patient = new Patient();
patient.PatientCovariates.Add(0, new());
_baselinePatients.TryAdd(i, patient);
}
// Try to copy the patients created in the baseline ConcurrentDictionary
for (int i = 0; i < _nArms; i++) {
for (int j = 0; j < _nPatients; j++) {
Patient patObjCopy = (Patient)_baselinePatients[j].Clone();
Patient patObjCopyTwo = (Patient)patObjCopy.Clone();
// patObjCopy should not be the same as patObjCopyTwo
// for i = 1 and j = 0 I get this error here: System.ArgumentException: 'An item with the same key has already been added. Key: Covariate'
patObjCopy.PatientCovariates[EXAMPLE_CYCLE].Add("Covariate for patient ", // To mark the arm name and make the patient struct different
j.ToString() +
" in arm " +
i.ToString());
// Save the patient copy in the _patientsCurrentArm WITHOUT changing the patient in _baselinePatients
_patientsCurrentArm.TryAdd(j, patObjCopy);
}
}
// Print out the value of Covariate for the first and second patient in EXAMPLE_CYCLE
Console.WriteLine(_patientsCurrentArm[0].PatientCovariates[EXAMPLE_CYCLE]["Covariate"]);
Console.WriteLine(_patientsCurrentArm[1].PatientCovariates[EXAMPLE_CYCLE]["Covariate"]);
}
internal struct Patient : ICloneable
{
///
/// Cycle, covariate name, covariate value
///
public Dictionary PatientCovariates
{ get; set; }
///
/// Initiates PatientCovariates
///
public Patient()
{
PatientCovariates = new();
}
///
/// Clone patients
///
///
public readonly object Clone()
{
Patient patient = (Patient)this.MemberwiseClone();
return patient;
}
}
}