2020年12月30日 星期三

C# 物件的複製

 C# 物件的複製

  • Shallow Copy - 使用 MemberwiseClone():

public Person ShallowCopy()
{
return this.MemberwiseClone() as Person;
}
  1. If a field is a value type, a bit-by-bit copy of the field is performed
  2. 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;
}
}


reference: https://dotblogs.com.tw/yc421206/2012/05/25/72390

沒有留言:

張貼留言