簡歷的深複製實現
workExperience類:實現了ICloeable接口==實現了Clone方法——創建一個新對象,然後將當前對象的非靜態字段複製到該新對象。如果字段是值類型的則對該字段執行逐位複製。如果字段是引用類型的,則複製引用但不復制引用的對象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Deep_Copy
{
class WorkExperience : ICloneable
{
private string workDate;
public string WorkDate
{
get { return workDate; }
set { this.workDate = value; }
}
private string company;
public string Company
{
get { return company; }
set { this.company = value; }
}
public object Clone()
{
return (Object)this.MemberwiseClone();
}
}
}
Resume簡歷
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Deep_Copy
{
class Resume : ICloneable
{
private string name;
private string sex;
private string age;
private WorkExperience workExperience;
public Resume(string name)
{
this.name = name;
workExperience = new WorkExperience();
}
private Resume(WorkExperience workExperience)
{
this.workExperience = (WorkExperience)workExperience.Clone();
}
public void SetPersonalInfo(string sex, string age)
{
this.sex = sex;
this.age = age;
}
public void SetWorkExperience(string workDate,string company)
{
this.workExperience.WorkDate = workDate;
this.workExperience.Company = company;
}
public void DisPlay()
{
Console.WriteLine("{0} {1} {2}", name, sex,age);
Console.WriteLine("工作經歷: {0} {1}",workExperience.WorkDate,workExperience.Company);
}
public Object Clone()
{
Resume obj = new Resume(this.workExperience);
obj.name = this.name;
obj.sex = this.sex;
obj.age = this.age;
return obj;
}
}
}
深複製:把引用對象的變量指向複製過的新對象,而不是原有的被引用的對象。當Resume類的對象new出來時候共有的Resume方法new了一個WorkExperience對象存儲到Resume對象中的workExperience。
Resume對象中的Clone方法 調用私有構造器Resume()將workExperience傳入到私有構造器中,在私有構造器中調用workExperienc中的Clone方法。 返回的WorkExperience對象存儲在workExperiecne中。這個時候相當於把引用對象的變量指向了複製過來的新對象obj 而不是原有的被引用的對象。