Как использовать icloneable интерфейс в C#
Hey, I'm attempting to clone an object. The Update Student Scores form should create a clone of the current student object and then apply changes to the clone. That way the changes will be saved to the current student only if the user clicks the OK button. To create a clone, the Student class will need to implement the ICloneable interface, and the Clone method will need to implement a deep copy. So far, I've learned that you want a deep copy of something when you need a copy of the other objects contained by the original (rather than pointers to the location of those objects in the original), so that when you make changes to these copied properties, you don't affect the original object. What I'm struggling with though is applying it to my model. Below is the student class I'm trying to clone and the update student form. I've also attached the source code if that helps. Thanks!
исходный текст
GitHub - Triptonix/Справка[^]
Студент.в CS
public class Student { public List<int> Scores = new List<int>(); public string Name { get; set; } public bool AddScore(int score) { try { Scores.Add(score); } catch { return false; } return true; } public List<int> GetScores() { return Scores; } public int GetScoreAt(int index) { return (int)Scores[index]; } public int GetScoreTotal() { int sum = 0; foreach (int score in Scores) { sum += score; } return sum; } public int GetScoreCount() { return Scores.Count; } public int GetScoreAverage() { return GetScoreTotal() / GetScoreCount(); } public void DestroyScores() { Scores = new List<int>(); } }
frmUpdateScores.в CS
public partial class frmUpdateStudent : Form { private Form1 parentForm; //main form private Student studentToEdit; //student list private int index; //index public frmUpdateStudent(Form1 parentForm, int index) //update parent form (Form1) with the new student and scores { this.parentForm = parentForm; this.index = index; studentToEdit = this.parentForm.GetStudent(index); InitializeComponent(); StudentName.Text = studentToEdit.Name; UpdateScoreDisplay(); } public void AddScoreToStudent(int value) //add score to current student and display in the list { studentToEdit.AddScore(value); UpdateScoreDisplay(); } public void UpdateScoreAtIndex(int id, int value) //update a score selected from the list { studentToEdit.GetScores()[id] = value; UpdateScoreDisplay(); } public int GetScoreAtIndex(int id) //get the score index { return studentToEdit.GetScoreAt(id); } private void UpdateScoreDisplay() //update the score display list { CurrentScores.DataSource = null; CurrentScores.DataSource = studentToEdit.GetScores(); } private void AddScoreButton_Click(object sender, EventArgs e) //open the add score form { frmAddScore addScoreForm = new frmAddScore(this); addScoreForm.Show(); } private void RemoveScoreButton_Click_1(object sender, EventArgs e) //remove a score from current index and update display list { studentToEdit.GetScores().RemoveAt(CurrentScores.SelectedIndex); UpdateScoreDisplay(); } private void ClearScoresButton_Click_1(object sender, EventArgs e) //clear all scores { studentToEdit.DestroyScores(); UpdateScoreDisplay(); } private void CloseButton_Click_1(object sender, EventArgs e) { Close(); //close form } private void UpdateButton_Click_1(object sender, EventArgs e) //open update form for current student { Student Form1 = new Student(); Form1.Name = StudentName.Text; parentForm.UpdateStudent(index, Form1); Close(); } private void UpdateScoresButton_Click(object sender, EventArgs e) { frmUpdateScore updateScoreForm = new frmUpdateScore(this, CurrentScores.SelectedIndex); updateScoreForm.Show(); } }
Что я уже пробовал:
Я пытался клонировать класс, но не знаю, как применить изменения только к клону, чтобы таким образом изменения были сохранены для текущего ученика только в том случае, если пользователь нажмет кнопку ОК
Gerry Schmitz
Те, кто знает, используют MemberwiseClone() для клонирования неглубоких частей ... так как вам не нужно пересматривать свой "пользовательский код", если вы только добавляете новые (не толстые) свойства.
https://docs.microsoft.com/en-us/dotnet/api/system.object.memberwiseclone?view=netframework-4.8