关于 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(); //深复制 } } }
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。