这段代码是怎么实现的深层拷贝?(code在里面)

崔鹏飞 崔鹏飞 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
class Student : ICloneable
{
public string Name;
public Int32 Age;

public Student(string name, Int32 age)
{
Name = name;
Age = age;
}

public void ShowInfo()
{
Console.WriteLine("{0}'s age is {1}", Name, Age);
}

public Object Clone()
{
//实现浅拷贝
return MemberwiseClone();
}
}

class Enrollment : ICloneable
{
//定义引用类型数据成员
public List<Student> students = new List<Student>();

//定义默认构造函数
public Enrollment()
{
}

//提供实现深拷贝的私有实例创建构造函数
private Enrollment(List<Student> studentList)
{
foreach (Student s in studentList)
{
students.Add((Student)s.Clone());
}
}

public void ShowEnrollmentInfo()
{
Console.WriteLine("Students enrollment information:");
foreach (Student s in students)
{
Console.WriteLine("{0}'s age is {1}", s.Name, s.Age);
}
}

public object Clone()
{
//执行浅拷贝
//return MemberwiseClone();
//执行深拷贝
return new Enrollment(students);
}
}
...全文

相关推荐

评论 12
收藏 已收藏
分享
返回顶部
崔鹏飞
C# 111,129 成员 642,538 内容