Это последующий вопрос к моему предыдущему, глубоко копируйте 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#
-
Anonymous
1740089851
Anonymous
Это последующий вопрос к моему предыдущему, глубоко копируйте 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;
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79455930/make-a-deep-copy-of-an-object-inside-a-concurrentdictionary-in-c-sharp[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия