浅复制的实现和解读
概念
“浅复制”,被复制对象的所有变量都含有与原来的对象相同的值,
而所有的对其他对象的的引用都任然指向原来的对象
简历的浅复制实现
工作经验
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shallow_copy
{
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; }
}
}
}
简历
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shallow_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();
}
//设置个人信息
public void SetPersonalInfo(string sex,string age)
{
this.sex = sex;
this.age = age;
}
//设置工作经历
public void SetWorkExperience(string workDate,string company)
{
workExperience.WorkDate = workDate;
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()
{
return (Object)MemberwiseClone();
}
}
}
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Shallow_copy
{
class Program
{
static void Main(string[] args)
{
Resume a = new Resume("强爸爸");
a.SetPersonalInfo("男", "20");
a.SetWorkExperience("1997-2000", "XXX公司");
Resume b = (Resume)a.Clone();
b.SetWorkExperience("1998-2000", "XXX公司");
Resume c = (Resume)a.Clone();
c.SetWorkExperience("1999-2000", "XXX公司");
a.DisPlay();
b.DisPlay();
c.DisPlay();
/*"浅复制",被复制对象的所有变量都含有与原来的对象相同的值,
* 而所有的对其他对象的的引用都任然指向原来的对象
*/
Console.ReadKey();
}
}
}
解读
**被复制对象的所有变量都含有与原来的对象相同的值:
而所有的对其他对象的引用都仍然指向原来的对象
理解——在Resume简历中有这么一句话 private WorkExperience workExperience
这个就是在Resume简历中有对WorkExperience的引用
都指向原来的对象——意为:在Resume的b和c使用SetWorkExperience都指向原来的对象 也就是a
所以最后c.SetWorkExperience修改结束后 其实修改的都是同一个对象 所以打印结果也会一直
就是由于Clone的Resume中有其他对象(WorkExperience)的引用 所以其实指向的就是同一个对象。