class CloneExample : ICloneable
{
private int m_data ;
private double m_data2 ;
public object Clone()
{
return this.MemberwiseClone();
}
public CloneExample()
{
}
public CloneExample(int data1, int data2)
{
m_data = data1;
m_data2 = data2;
}
public override string ToString()
{
return String.Format("[d1,d2] {0} {1}", m_data, m_data2);
}
}
class Program
{
static void Main(string[] args)
{
CloneExample aEx = new CloneExample(10,20);
CloneExample aEx2 = (CloneExample)aEx.Clone();
Console.WriteLine("the first object value is {0}", aEx.ToString());
Console.WriteLine("the first object value is {0}", aEx2.ToString());
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)
Memberwiseclone首先可能使用Activator.CreateInstance创建实例,然后迭代该类型中的所有字段并将值设置为相应的成员/字段.
但我宁愿根本不使用ICloneable.如果我需要使用克隆,我使用BinaryFormatter序列化对象图,然后反序列化它,以便我得到新的深度克隆实例.