- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace 对象浅度克隆演示
- {
- //对象的浅copy,只copy值类型的副本,而引用类型复制地址
- class Program
- {
- static void Main( string[] args )
- {
- Student stu = new Student();
- stu.Age = 23;
- stu.StuID = "20222222";
- stu.Per = new Person();
- stu.Per.Age = 800;
- stu.Per.Name = " aladdin ";
- Console.WriteLine( "未复制前: stu.Age {0} stu.StuID {1} stu.Per.Age {2} stu.Per.Name {3} " , stu.Age , stu.StuID , stu.Per.Age , stu.Per.Name );
- Student stu2 = stu.CopyObj();
- stu2.Age = 223333;
- stu2.StuID = "201111111";
- stu2.Per.Age = 500;
- stu2.Per.Name = "zhaohaifu";
- Console.WriteLine( "复制后: stu.Age {0} stu.StuID {1} stu.Per.Age {2} stu.Per.Name {3} " , stu.Age , stu.StuID , stu.Per.Age , stu.Per.Name );
- //可以看出,stu的值类型没有变,而引用类型因为是传地址,所以浅copy之后仍然可以操作原对象
- Console.ReadLine();
- }
- }
- class Person
- {
- private string _name;
- private int _age;
- public string Name
- {
- get
- {
- return this._name;
- }
- set
- {
- this._name = value;
- }
- }
- public int Age
- {
- get
- {
- return this._age;
- }
- set
- {
- this._age = value;
- }
- }
- }
- class Student
- {
- private string _stuID;
- private Person _per;
- private int _age;
- public int Age
- {
- get
- {
- return this._age;
- }
- set
- {
- this._age = value;
- }
- }
- public Person Per
- {
- get
- {
- return this._per;
- }
- set
- {
- this._per = value;
- }
- }
- public string StuID
- {
- get
- {
- return this._stuID;
- }
- set
- {
- this._stuID = value;
- }
- }
- public Student CopyObj()
- {
- return ( Student )this.MemberwiseClone();
- }
- }
- }
C#中的对象浅拷贝
最新推荐文章于 2024-04-16 15:30:28 发布