深度复制

转自:http://www.cnblogs.com/sunway/archive/2010/01/19/1651554.html

如果每个对象都要这样去进行深度复制的话就太麻烦了,我们可以利用串行化/反串行化来对对象进行深度复制:先把对象串行化(Serialize)到内存中,然后再进行反串行化,通过这种方式来进行对象的深度复制:

public object Clone() {
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, this);
    ms.Position = 0;

    return (bf.Deserialize(ms)); ;

}

我们来做一个测试:

class Program {
    static void Main(string[] args) {
       RefPoint rPoint = new RefPoint(1);
       ValPoint vPoint = new ValPoint(2);

       RefLine line = new RefLine(rPoint, vPoint);
       RefLine newLine = (RefLine)line.Clone();
                 
       Console.WriteLine("Original line.rPoint.x = {0}", line.rPoint.x);
       Console.WriteLine("Cloned newLine.rPoint.x = {0}", newLine.rPoint.x);

       line.rPoint.x = 10;   // 改变原对象 引用成员 的值
       Console.WriteLine("Original line.rPoint.x = {0}", line.rPoint.x);
       Console.WriteLine("Cloned newLine.rPoint.x = {0}", newLine.rPoint.x);
    }
}
输出为:
Original line.rPoint.x = 1
Cloned newLine.rPoint.x = 1
Original line.rPoint.x = 10
Cloned newLine.rPoint.x = 1

可见,两个对象的引用成员已经分离,改变原对象的引用对象的值,并不影响复制后的对象。

这里需要注意:如果想将对象进行序列化,那么对象本身,及其所有的自定义成员(类、结构),都必须使用Serializable特性进行标记。所以,如果想让上面的代码运行,我们之前定义的类都需要进行这样的标记:

[Serializable()]
public class RefPoint { /*略*/}

NOTE:关于特性(Attribute),可以参考 .Net 中的反射(反射特性) 一文。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值