Net复习笔记:第七部分:浅拷贝和深拷贝

浅拷贝:(shallow copy)

深拷贝:(deep copy)

  1. 性能问题,深拷贝要对整个结构树拷贝,性能影响较大
  2. 可行性,对整个结构树拷贝,在很多情况下不能实现
  3. 稳定性,某些字段涉及循环,深拷贝可能进入死循环
  4. 简单,浅拷贝在实现上面比较的简单
  5. String(是引用类型的深拷贝实例)

浅拷贝:只要调用继承来的MenberwiseClone()方法就可以啦

深拷贝:要new一个新的对象,然后把内容全部添加进去

namespace NetNiBiXiuZhiDao

{

    public partial class WebForm11 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            Enrollment sourcestudentslist = new Enrollment();

            sourcestudentslist.stud.Add(new Student("elong", 12));

            sourcestudentslist.stud.Add(new Student("tuan", 13));

 

            Enrollment clonestudentslist = sourcestudentslist.NewClone() as Enrollment;

            sourcestudentslist.ShowEnrollmentinfo();

            clonestudentslist.ShowEnrollmentinfo();

 

            clonestudentslist.stud[1].Age = 14;

            clonestudentslist.stud[1].Name = "hotel";

 

            sourcestudentslist.ShowEnrollmentinfo();

            clonestudentslist.ShowEnrollmentinfo();

        }

    }

 

    class Enrollment : ICloneable

    {

        HttpResponse res = HttpContext.Current.Response;

        public List<Student> stud = new List<Student>();

        public Enrollment()

        { }

 

        public Enrollment(List<Student> studli)

        {

            foreach (Student s in studli)

            {

                stud.Add((Student)s.Clone());

            }

        }

 

        public void ShowEnrollmentinfo()

        {

            res.Write("Student :Enrollment<br>");

            foreach (Student str in stud)

            {

                res.Write(string.Format("{0}:{1}", str.Name, str.Age+"<br>"));

            }

        }

 

        public object Clone()

        {

            return MemberwiseClone();

        }

 

        public object NewClone()

        {

            return new Enrollment(stud);

        }

    }

 

    class Student

    {

        HttpResponse res = HttpContext.Current.Response;

        public string Name;

        public int Age;

        public Student(string name, int age)

        {

            Name = name;

            Age = age;

        }

 

        public void Showinfo()

        {

            res.Write(string.Format("{0}:{1}",Name,Age));

        }

 

        public object Clone()

        {

            return MemberwiseClone();

        }

    }

}

 

posted @ 2014-01-23 16:49  瀚海行舟  阅读(162)  评论(0)    收藏  举报