C# ICloneable,shallow clone,deep clone.
程序员文章站
2022-07-02 13:18:43
1 [Serializable] 2 public class Person:ICloneable 3 { 4 public string Name { get; set; } 5 public int Id { get; set; } 6 public int Age { get; set; } ... ......
1 [serializable] 2 public class person:icloneable 3 { 4 public string name { get; set; } 5 public int id { get; set; } 6 public int age { get; set; } 7 public department department { get; set; } 8 9 public object clone() 10 { 11 return this.memberwiseclone(); 12 } 13 14 15 public person shallowclone() 16 { 17 return clone() as person; 18 } 19 20 public person deepclone() 21 { 22 using (stream objstream = new memorystream()) 23 { 24 iformatter formatter = new binaryformatter(); 25 formatter.serialize(objstream, this); 26 objstream.seek(0, seekorigin.begin); 27 return formatter.deserialize(objstream) as person; 28 } 29 } 30 } 31 32 [serializable] 33 public class department 34 { 35 public string deptname { get; set; } 36 public int deptid { get; set; } 37 }
1 class program 2 { 3 static void main(string[] args) 4 { 5 clonedemo(); 6 console.readline(); 7 } 8 9 static void clonedemo() 10 { 11 person fred = new person() 12 { 13 id = 1, 14 name = "fred", 15 age = 32, 16 department=new department() 17 { 18 deptid=1, 19 deptname="dept1" 20 } 21 }; 22 23 console.writeline($"fred,name:{fred.name},id:{fred.name},department name:{fred.department.deptname},deptid:{fred.department.deptid}"); 24 25 person shallowcloneperson = fred.shallowclone() as person; 26 console.writeline($"shallowcloneperson,name:{shallowcloneperson.name},id:{shallowcloneperson.id},department name:{shallowcloneperson.department.deptname},deptid:{shallowcloneperson.department.deptid}"); 27 28 fred.id = 2; 29 fred.name = "fred2"; 30 fred.age = 33; 31 fred.department.deptid = 2; 32 fred.department.deptname = "dept2"; 33 console.writeline($"shallowcloneperson,name:{shallowcloneperson.name},id:{shallowcloneperson.id},department name:{shallowcloneperson.department.deptname},deptid:{shallowcloneperson.department.deptid}"); 34 35 36 person deepcloneperson = fred.deepclone() as person; 37 console.writeline($"deepcloneperson,name:{deepcloneperson.name},id:{deepcloneperson.id},department name:{deepcloneperson.department.deptname},id:{deepcloneperson.department.deptid}"); 38 39 fred.id = 3; 40 fred.name = "fred3"; 41 fred.age = 34; 42 fred.department.deptid = 3; 43 fred.department.deptname = "dept3"; 44 console.writeline($"deepcloneperson,name:{deepcloneperson.name},id:{deepcloneperson.id},department name:{deepcloneperson.department.deptname},id:{deepcloneperson.department.deptid}"); 45 } 46 }
下一篇: 以一道ctf学习python脚本