最近在看设计模式,看到原型模式,里面讲到了这两个东西,就顺便来仔细研究一下这个。
怎么说
浅复制:被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象引用对任然指向原来的对象。就是改变原来对象引用值是会同时改变复制出来的对象中的值。
深复制:把引用对象的变量指向复制过的新对象,而不是原有的被引用的对象。简单的说就是把引用中的值也一起复制了。
ICloneable
这个接口是C#系统自带的一个复制的接口,只用实现它就可以了。具体内容如下
public interface ICloneable{
object Clone();
}
实例
这个是MSDN里给的例子,稍微改动了一下。
public class IdInfo:ICloneable
{
public int IdNumber;
public IdInfo(int IdNumber)
{
this.IdNumber = IdNumber;
}
public object Clone()//浅复制
{
return (IdInfo)this.MemberwiseClone();
}
}
public class Person
{
public int Age;
public string Name;
public IdInfo IdInfo;
public Person ShallowCopy()//浅复制
{
return (Person) this.MemberwiseClone();
}
public Person DeepCopy()//深复制
{
//new IdInfo的做法
//Person other = (Person) this.MemberwiseClone();
//other.IdInfo = new IdInfo(IdInfo.IdNumber);
//other.Name = String.Copy(Name);
//new Person 的做法
//Person other =new Person();
//other.IdInfo =this.IdInfo.Clone();
//other.Name = String.Copy(Name);
//other.Age= this.Age;
return other;
}
}
public class Example
{
public static void Main()
{
// Create an instance of Person and assign values to its fields.
Person p1 = new Person();
p1.Age = 42;
p1.Name = "Sam";
p1.IdInfo = new IdInfo(6565);
// Perform a shallow copy of p1 and assign it to p2.
Person p2 = p1.ShallowCopy();
// Display values of p1, p2
Console.WriteLine("Original values of p1 and p2:");
Console.WriteLine(" p1 instance values: ");
DisplayValues(p1);
Console.WriteLine(" p2 instance values:");
DisplayValues(p2);
// Change the value of p1 properties and display the values of p1 and p2.
p1.Age = 32;
p1.Name = "Frank";
p1.IdInfo.IdNumber = 7878;
Console.WriteLine("\nValues of p1 and p2 after changes to p1:");
Console.WriteLine(" p1 instance values: ");
DisplayValues(p1);
Console.WriteLine(" p2 instance values:");
DisplayValues(p2);
// Make a deep copy of p1 and assign it to p3.
Person p3 = p1.DeepCopy();
// Change the members of the p1 class to new values to show the deep copy.
p1.Name = "George";
p1.Age = 39;
p1.IdInfo.IdNumber = 8641;
Console.WriteLine("\nValues of p1 and p3 after changes to p1:");
Console.WriteLine(" p1 instance values: ");
DisplayValues(p1);
Console.WriteLine(" p3 instance values:");
DisplayValues(p3);
}
public static void DisplayValues(Person p)
{
Console.WriteLine(" Name: {0:s}, Age: {1:d}", p.Name, p.Age);
Console.WriteLine(" Value: {0:d}", p.IdInfo.IdNumber);
}
}
运行结果
网友评论