浅复制:复制出来一个对象,但对象中的引用没有被复制,而是与原来的对象公用,改变一个,另一个也跟着变
public School Copy()
{
return (School)this.MemberwiseClone();
}
return (School)this.MemberwiseClone();
}
注意:浅复制可以复制的有: 值类型(int,float)
:字符串string也能被复制
深复制:复制出来一个对象,对象中的引用同时也被复制,就是完全复制;
public School DeepCopy()
{
School school;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
school = (School)formatter.Deserialize(memoryStream);
return school;
}
{
School school;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
school = (School)formatter.Deserialize(memoryStream);
return school;
}
注意:深复制可以复制全部,但是要被复制的类必须能够被序列化,而且它里面的引用类型也必须能够被序列化,
序列化一个类就是在类的前面加[Serializable]