
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
public class Simple:ICloneable
{
private int field1;
private int field2;
public int Property1
{
get
{
return field1;
}
set
{
field1 = value;
}
}
public int Property2
{
get
{
return field2;
}
set
{
field2 = value;
}
}
public object Clone()
{
return this.MemberwiseClone();
}
}
public class Complecated:ICloneable
{
private Simple simple;
public Complecated()
{
simple = new Simple();
}
private Complecated(Simple s)
{
simple = (Simple)s.Clone();
}
public object Clone()
{
Complecated c = new Complecated(simple );
return c;
}
public void SetMe(int a,int b)
{
simple.Property1 = a;
simple.Property2 = b;
}
public void Show()
{
Console.WriteLine(simple.Property1);
Console.WriteLine(simple.Property2);
}
}
public class Client
{
public static void Main()
{
Complecated c = new Complecated();
c.SetMe(1, 2);
Complecated c2 = (Complecated )c.Clone();
c2.SetMe(3, 4);
c.Show();
c2.Show ();
Console.Read();
}
}
}
本文通过C#代码示例介绍了深拷贝与浅拷贝的概念及其实现方式,展示了如何为包含简单类型成员变量的对象进行拷贝,并演示了当对象内部含有引用类型时如何确保拷贝的独立性。
1251

被折叠的 条评论
为什么被折叠?



