Deep Copy in C# (Cloning for a user defined class)

来源:互联网 发布:单片机和plc的前景 编辑:程序博客网 时间:2024/05/21 11:32

原文:http://www.c-sharpcorner.com/UploadFile/sd_surajit/cloning05032007012620AM/cloning.aspx

  
Have you ever used the Clone() method of DataSet? This method creates an empty class with same structure as original DataSet.
 
You can write your own clonable classes. To do so, you must implement IClonable. The following code shows a clonable Test class.
 
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public
{
    public Test()
    {
    }
    // deep copy in separeate memory space
    public object Clone()
    {
        MemoryStream ms = new MemoryStream();
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, this);
        ms.Position = 0;
        object obj = bf.Deserialize(ms);
        ms.Close();
        return obj;
    }
}
Class Test : IClonable
原创粉丝点击