C# 物件的複製
- Shallow Copy - 使用 MemberwiseClone():
public Person ShallowCopy()
{
return this.MemberwiseClone() as Person;
}
{
return this.MemberwiseClone() as Person;
}
- If a field is a value type, a bit-by-bit copy of the field is performed
- If a field is a reference type, the reference is copied but the referred object is not
- Deep Clone - 使用 BinaryFormatter() 序列化(Serialize)
public Person DeepClone()
{
using (var memory = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(memory, this);
memory.Seek(0, SeekOrigin.Begin); // Set the position to the beginning of the stream.
return formatter.Deserialize(memory) as Person;
}
}
{
using (var memory = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(memory, this);
memory.Seek(0, SeekOrigin.Begin); // Set the position to the beginning of the stream.
return formatter.Deserialize(memory) as Person;
}
}
reference: https://dotblogs.com.tw/yc421206/2012/05/25/72390
沒有留言:
張貼留言