Re: [問題] 陣列複製問題List<class>

看板C_Sharp (C#)作者 (s4300026)時間3年前 (2020/11/12 20:46), 3年前編輯推噓1(102)
留言3則, 2人參與, 3年前最新討論串2/2 (看更多)
假設你有一群學生要複製 每個學生有一堆考試成績 和 一個班導師 把學生複製出來時, 依你的需求, 裡面的考試成績 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, 3年前 , 1F
如果你想要全部都是深層複製,我聽說 serialize
11/12 20:54, 1F

11/12 20:54, 3年前 , 2F
可以達成該目的
11/12 20:54, 2F
※ 編輯: s4300026 (42.73.222.21 臺灣), 11/12/2020 20:56:03

11/17 12:23, 3年前 , 3F
謝謝~目前這個方法好像正是我需要的
11/17 12:23, 3F
文章代碼(AID): #1VhIwKTz (C_Sharp)
文章代碼(AID): #1VhIwKTz (C_Sharp)