作者a210s02 (蟲蟲)
看板C_Sharp
標題Re: [問題] 如何把父類別的資料複製到子類別?
時間Thu Sep 8 15:44:23 2011
※ 引述《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
1F:→ apiod:我的類別和屬性都非常多 這樣一個一個寫會很累 09/08 15:49
2F:→ apiod:我是想知道有沒有比較快速的方法 09/08 15:49
3F:→ kinwind:用Reflection 09/08 17:08
4F:→ hanyan:不要用繼承,使B裡面有個ref A如何? 09/08 19:18
5F:→ a210s02:用List呢? 09/08 19:35
6F:→ yeo1987:直接ref傳過去真的比較簡單- - 09/08 20:53
7F:→ suching:能不能假裝B是A, 然後反序列化地接受A序列化後的資料? 09/15 04:41
8F:→ ssccg:在constructor用Reflection迴圈比對Property的名字填資料 09/18 00:06