理解:通过在类中定义一个Clone方法克隆自己,分为深COPY 和 浅COPY; 现在NET中,继承了ICloneable接口的类都可以重写Clone()方法。
代码:
//原型类
[Serializable]
public abstract class PrototypeClass
{
public string _myValue;
public string MyValue
{
get { return _myValue; }
set { _myValue = value; }
}
public abstract PrototypeClass Clone();
}
//浅拷贝
public class ShallowClone:PrototypeClass
{
public ShallowClone(string value)
{
this._myValue = value;
}
public override PrototypeClass Clone()
{
return (PrototypeClass)this.MemberwiseClone();
}
}
//深拷贝
[Serializable]
public class DeepClone : PrototypeClass
{
public DeepClone(string value)
{
this._myValue = value;
}
public override PrototypeClass Clone()
{
PrototypeClass deepObject;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
deepObject = (PrototypeClass)formatter.Deserialize(memoryStream);
return deepObject;
}
}
[Serializable]
public abstract class PrototypeClass
{
public string _myValue;
public string MyValue
{
get { return _myValue; }
set { _myValue = value; }
}
public abstract PrototypeClass Clone();
}
//浅拷贝
public class ShallowClone:PrototypeClass
{
public ShallowClone(string value)
{
this._myValue = value;
}
public override PrototypeClass Clone()
{
return (PrototypeClass)this.MemberwiseClone();
}
}
//深拷贝
[Serializable]
public class DeepClone : PrototypeClass
{
public DeepClone(string value)
{
this._myValue = value;
}
public override PrototypeClass Clone()
{
PrototypeClass deepObject;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
deepObject = (PrototypeClass)formatter.Deserialize(memoryStream);
return deepObject;
}
}