109,339
社区成员




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);
}
}
public Object Clone()
{
//实现浅拷贝
return MemberwiseClone();
}
public Object Clone()
{
return new Student(Name, Age);
}
public object Clone()
{
return new Enrollment(students);
//这里传的参数是原来旧对象的students
}
private Enrollment(List<Student> studentList)
{
foreach (Student s in studentList)
{
students.Add((Student)s.Clone());
//在这个私有的构造函数里面写的students是新的实例的students
}
}
return new Enrollment(students);
[Quote=引用 2 楼 gomoku 的回复:]foreach (Student s in studentList)
{
students.Add((Student)s.Clone());
}