Re: [問題] 如何把父類別的資料複製到子類別?

看板C_Sharp (C#)作者 (蟲蟲)時間14年前 (2011/09/08 15:44), 編輯推噓0(008)
留言8則, 7人參與, 最新討論串2/2 (看更多)
※ 引述《apiod ( )》之銘言: : public class A : { : public string FirstName { get; set; } : public string LastName { get; set; } : public string Address { get; set; } : } : public class B : A : { : public string company { get;set;} /*新增這邊*/ public B(A x) { this.FirstName = x.FisrstName; this.SecondName = x.SecondName; this.Address = x.Address; } : } : A a = new A(); : a.FirstName = "xx1"; : a.LastName = "xx2"; : a.Address = "xx3"; //方法1需要新增上面的部分 B b = new B(a); //方法2 B b = new B(); b.FisrstName = a.FistName; b.SecondName = a.SecondName; b.Address = a.Address; : 請問我該如何把A的資料複製給B呢? : 感謝解惑 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.122.36.38

09/08 15:49, , 1F
我的類別和屬性都非常多 這樣一個一個寫會很累
09/08 15:49, 1F

09/08 15:49, , 2F
我是想知道有沒有比較快速的方法
09/08 15:49, 2F

09/08 17:08, , 3F
用Reflection
09/08 17:08, 3F

09/08 19:18, , 4F
不要用繼承,使B裡面有個ref A如何?
09/08 19:18, 4F

09/08 19:35, , 5F
用List呢?
09/08 19:35, 5F

09/08 20:53, , 6F
直接ref傳過去真的比較簡單- -
09/08 20:53, 6F

09/15 04:41, , 7F
能不能假裝B是A, 然後反序列化地接受A序列化後的資料?
09/15 04:41, 7F

09/18 00:06, , 8F
在constructor用Reflection迴圈比對Property的名字填資料
09/18 00:06, 8F
文章代碼(AID): #1EQ79QmV (C_Sharp)
文章代碼(AID): #1EQ79QmV (C_Sharp)