Сделайте глубокую копию объекта в C# с частными переменными и объектами ReadonlyC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Сделайте глубокую копию объекта в C# с частными переменными и объектами Readonly

Сообщение 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;
}
}
}


Подробнее здесь: https://stackoverflow.com/questions/794 ... es-and-obj
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»