简历实例
(一)浅拷贝
1.简历实例
public class Remuse : ICloneable { private string name; private string sex; private string age; private WorkExperience work; public Remuse(string name) { this.name = name; work = new WorkExperience(); } //设置个人信息 public void SetPersonalInfo(string sex, string age) { this.sex = sex; this.age = age; } //设置工作经历 public void SetWorkExperience(string workDate, string company) { work.WorkDate = workDate; work.Company = company; } //显示 public void Display() { Console.WriteLine("{0} {1} {2}", name, sex, age); Console.WriteLine("工作经历:{0} {1}", work.WorkDate, work.Company); } public object Clone() { return (object)this.MemberwiseClone(); } }
2.工作经验
public class WorkExperience { private string workDate; public string WorkDate { get { return workDate; } set { workDate = value; } } private string company; public string Company { get { return company; } set { company = value; } } }
3.调用
Remuse a = new Remuse("大鸟"); a.SetPersonalInfo("男", "29"); a.SetWorkExperience("1998-2000", "XX公司"); Remuse b = (Remuse)a.Clone(); b.SetWorkExperience("1998-2006", "YY企业"); Remuse c = (Remuse)a.Clone(); c.SetPersonalInfo("男", "24"); a.Display(); b.Display(); c.Display();
(二)深拷贝
1.简历
public class RemuseDeep : ICloneable { private string name; private string sex; private string age; private WorkExperienceDeep work; public RemuseDeep(string name) { this.name = name; work = new WorkExperienceDeep(); } private RemuseDeep(WorkExperienceDeep work) //提供Clone方法调用的私有构造函数,以便克隆工作经历数据, { this.work = (WorkExperienceDeep)work.Clone(); } //设置个人信息 public void SetPersonalInfo(string sex, string age) { this.sex = sex; this.age = age; } //设置工作经历 public void SetWorkExperience(string workDate, string company) { work.WorkDate = workDate; work.Company = company; } //显示 public void Display() { Console.WriteLine("{0} {1} {2}", name, sex, age); Console.WriteLine("工作经历:{0} {1}", work.WorkDate, work.Company); } public Object Clone() { RemuseDeep obj = new RemuseDeep(this.work); //调用私有构造函数,克隆工作经历,在给简历相关字段赋值,最终返回深复制简历对象, obj.name = this.name; obj.sex = this.sex; obj.age = this.age; return obj; } }
2.工作经验
public class WorkExperienceDeep:ICloneable { private string workDate; public string WorkDate { get { return workDate; } set { workDate = value; } } private string company; public string Company { get { return company; } set { company = value; } } public Object Clone() //工作经历类实现Clone方法, { return (Object)this.MemberwiseClone(); } }
3.调用
RemuseDeep ad = new RemuseDeep("大鸟"); ad.SetPersonalInfo("男", "29"); ad.SetWorkExperience("1998-2000", "XX公司"); RemuseDeep bd = (RemuseDeep)ad.Clone(); bd.SetWorkExperience("1998-2006", "YY企业"); RemuseDeep cd = (RemuseDeep)ad.Clone(); cd.SetWorkExperience("1998-2003", "ZZ企业"); ad.Display(); bd.Display(); cd.Display();
总结:浅拷贝:不会复制引用类型的数据。深拷贝:会复制引用类型的数据