實現(xiàn)深復制的思路為:先將類序列化到內(nèi)存中,然后從內(nèi)存中反序列化回來,就可實現(xiàn)深復制。
有類:
[Serializable]
class Product
{
public string Name { get; set; }
public int CategoryID { get; set; }
}
序列化代碼:
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
Product p1 = new Product() { Name = "", CategoryID = 1 };
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, p1);
stream.Position = 0;
Product p = new Product();
p= formatter.Deserialize(stream) as Product;