代码改变世界

关于 C# 中的 ICloneable 测试

2011-06-16 14:14  音乐让我说  阅读(331)  评论(0编辑  收藏  举报

我们不想要下面的效果:

using System;

namespace ConAppTestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = new Student()
            {
                Id = 1,
                Name = "张三",
                Age = 18
            };

            Student stu2 = stu1;
            Console.WriteLine(stu2.Name); //张三
            stu2.Name = "李四";

            Console.WriteLine(stu1.Name); //李四
            Console.WriteLine(stu2.Name); //李四
        }
    }

    class Student : ICloneable
    {
        public int Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }

        public Student Mather
        {
            get;
            set;
        }

        public object Clone()
        {
            return this.MemberwiseClone(); //深复制
        }
    }
}

所以要用到 克隆。

代码如下:

using System;

namespace ConAppTestDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student stu1 = new Student()
            {
                Id = 1,
                Name = "张三",
                Age = 18,
                Mather = new Student()
                    {
                         Id = 2,
                          Name = "东方红",
                          Age = 40
                    }
            };

            Student stu2 = (Student)stu1.Clone();
            Console.WriteLine(stu2.Name); //张三
            Console.WriteLine(stu2.Mather.Name);  //东方红
            stu2.Name = "李四";

            Console.WriteLine(stu1.Name); //张三
            Console.WriteLine(stu2.Name); //李四
        }
    }

    class Student : ICloneable
    {
        public int Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }

        public Student Mather
        {
            get;
            set;
        }

        public object Clone()
        {
            return this.MemberwiseClone(); //深复制
        }
    }
}

谢谢浏览!