Это следующий вопрос к моему предыдущему, сделайте глубокую копию объекта внутри ConcurrentDictionary в C#. Я хочу клонировать свой пациент объект, чтобы объект partientCovariates одинаково для копирования.
Но когда я это делаю, я также также Хочу регенерировать случайный CRN к тому же объекту, который был создан, когда пациент struct был построен с использованием _seed .
В то же время , Я хотел бы Держите CRN readonly и _seed private и readonly . Это возможно? < /P>
using System.Collections.Concurrent;
using System.Text.Json;
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 treatments
int _nArms = 2;
int _nPatients = 5;
// Add patients at baseline to _baselinePatients
for (int i = 0; i < _nPatients; i++) {
Patient patient = new Patient(1);
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.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);
}
}
}
internal struct Patient : ICloneable
{
private readonly int _seed; // used when the object is copied to regenerated the Crn
public readonly Random Crn { get; }
///
/// Cycle, covariate name, covariate value
///
public Dictionary PatientCovariates
{ get; set; }
///
/// Initiates PatientCovariates
///
public Patient(int seed)
{
_seed = seed;
Crn = new(_seed);
PatientCovariates = new();
}
///
/// Clone patients
///
///
public readonly object Clone()
{
Patient patient = new() {
// Here, I also want to regenerate the Crn by using _seed, as was done when the patient was constructed
PatientCovariates = this.PatientCovariates.ToDictionary(
entry => entry.Key,
entry => entry.Value.ToDictionary(
innerEntry => innerEntry.Key,
innerEntry => innerEntry.Value
)
)
};
return patient;
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... es-and-obj
Сделайте глубокую копию объекта в C# с частными переменными и объектами Readonly ⇐ C#
Место общения программистов C#
1740092756
Anonymous
Это следующий вопрос к моему предыдущему, сделайте глубокую копию объекта внутри ConcurrentDictionary в C#. Я хочу клонировать свой пациент объект, чтобы объект partientCovariates одинаково для копирования.
Но когда я это делаю, я также также Хочу регенерировать случайный CRN к тому же объекту, который был создан, когда пациент struct был построен с использованием _seed .
В то же время , Я хотел бы Держите CRN readonly и _seed private и readonly . Это возможно? < /P>
using System.Collections.Concurrent;
using System.Text.Json;
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 treatments
int _nArms = 2;
int _nPatients = 5;
// Add patients at baseline to _baselinePatients
for (int i = 0; i < _nPatients; i++) {
Patient patient = new Patient(1);
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.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);
}
}
}
internal struct Patient : ICloneable
{
private readonly int _seed; // used when the object is copied to regenerated the Crn
public readonly Random Crn { get; }
///
/// Cycle, covariate name, covariate value
///
public Dictionary PatientCovariates
{ get; set; }
///
/// Initiates PatientCovariates
///
public Patient(int seed)
{
_seed = seed;
Crn = new(_seed);
PatientCovariates = new();
}
///
/// Clone patients
///
///
public readonly object Clone()
{
Patient patient = new() {
// Here, I also want to regenerate the Crn by using _seed, as was done when the patient was constructed
PatientCovariates = this.PatientCovariates.ToDictionary(
entry => entry.Key,
entry => entry.Value.ToDictionary(
innerEntry => innerEntry.Key,
innerEntry => innerEntry.Value
)
)
};
return patient;
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79456013/make-a-deep-copy-of-an-object-in-c-sharp-with-private-readonly-variables-and-obj[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия