Это последующий вопрос к моему предыдущему, глубоко копируйте concurrentdictionary в C#, который не содержал достаточной информации, чтобы получить должным образом. < /p>
Я пытаюсь сделать Глубокая копия объекта, пациент , в concurrentdictionary , _baselinepatients , к другому concurrentdictionary , _patientCurrentarm , в C#, но не удастся. Кажется, что пациент, которого я копирую из _baselinepatients до _patientcurrentarm - это просто указатель, несмотря на использование memberwiseclone при клонировании пациента.
Это связано с тем фактом, что два concurrentdictionaries _baselinepatients и _patientCurrentarm Содержит те же типы данных? уже добавлено. Ключ: Covariate '
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;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... in-c-sharp
Сделайте глубокую копию объекта внутри concurrentdictionary в C# ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Сделайте глубокую копию объекта в C# с частными переменными и объектами Readonly
Anonymous » » в форуме C# - 0 Ответы
- 12 Просмотры
-
Последнее сообщение Anonymous
-