Re: [問題] 陣列複製問題List<class>
假設你有一群學生要複製
每個學生有一堆考試成績 和 一個班導師
把學生複製出來時, 依你的需求, 裡面的考試成績 class 要 new 一份 (DeepClone)
***** 但其他的class, 如 班導師 class 要怎麼處理呢? *****
像是班導師就應該複製參考(MemberwiseClone / ShallowClone), 因為當老師改名時,
你會希望你新複製出來的學生的老師名字要一起改.
因此我的想法是, 你就乖乖為每個你自己定義的class寫下Clone方法
你可以繼承 ICloneable, 這樣就不會出現相同方法, 不同方法名的問題
如:
PartialClone(); Clone(); clone(); MyClone();......
-------------------
class Teacher
{
String name;
}
class Exam
{
public:
String exam_type;
int total_score;
List<int> sub_score;
Exam Clone()
{
Exam obj = new Exam();
obj.exam_type = exam_type;
obj.total_score = total_score;
obj.sub_score = new List<int>();
foreach(int item in sub_score)
{
obj.sub_score.Add(item);
}
}
}
class Student
{
public:
String name;
Teacher teacher_ref;
List<Exam> terms_exams;
Student Clone()
{
Student obj = new Student();
obj.name = name;
obj.teacher_ref = teacher_ref;
obj.terms_exams = new List<Exam>();
foreach(Exam item in terms_exams)
{
obj.terms_exams.Add(item.Clone());
}
}
}
List<Student> students_lst;
List<Student> students_lst_2;
foreach(Student item in students_lst)
{
students_lst_2.Add(item.Clone());
}
********************************
如果你問我的作法, 我會把我的物件繼承 Object,
因為他有撰寫 Object.MemberwiseClone 方法
先用該方法把所有內容進行 淺層複製, 即 "值用值複製, 參考用參考複製"
然後再針對需要 深層複製 的地方做額外撰寫.
Student Clone()
{
Student obj = this.MemberwiseClone() as Student;
obj.terms_exams = new List<Exam>();
foreach(Exam item in terms_exams)
{
obj.terms_exams.Add(item.Clone());
}
}
以上是我的想法啦..
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 42.73.222.21 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_Sharp/M.1605185172.A.77D.html
※ 編輯: s4300026 (42.73.222.21 臺灣), 11/12/2020 20:49:04
→
11/12 20:54,
4年前
, 1F
11/12 20:54, 1F
→
11/12 20:54,
4年前
, 2F
11/12 20:54, 2F
※ 編輯: s4300026 (42.73.222.21 臺灣), 11/12/2020 20:56:03
推
11/17 12:23,
4年前
, 3F
11/17 12:23, 3F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
C_Sharp 近期熱門文章
PTT數位生活區 即時熱門文章