现在的位置: 首页 > 综合 > 正文

[C#高质量代码的建议]浅拷贝与深拷贝

2013年12月08日 ⁄ 综合 ⁄ 共 580字 ⁄ 字号 评论关闭

一个简单的浅拷贝实现代码:

class Sample : iCloneable
{
    public String Name {get; set;}
    public object Clone()
    {
        return this.memberwiseClone();
    }
}

用法如下:

Sample sample1 = new Sample {Name="wlc"};
Sample sample2 = sample1.Clone as Sample;

浅拷贝中,值的拷贝是不可修改的,引用的拷贝的内容是可以修改的。

同时实现深拷贝跟浅拷贝,模型如下:

class Sample : iCloneable
{
    public String Name {get; set;}
    public object Clone()
    {
        return this.memberwiseClone();
    }
    public Sample DeepClone()
    {
        using (Stream object = new MemorySream())
       {
            IFormatter if = new BinaryFormatter();
            if.Serialize(object, this);
            object.Seek(0, SeekOrigin.Begin);
             return if.Deserialize(object) as Sample;
        }
    }
    public Sample ShallowClone()
    {
        return Clone() as Sample;
    }
}

抱歉!评论已关闭.