/// <summary>
/// Clone Object
/// </summary>
/// <returns></returns>
public static T Clone<T>(T obj)
{
T cloned = default(T);
var serializer = new DataContractSerializer(typeof(T));
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
ms.Position = 0;
cloned = (T)serializer.ReadObject(ms);
}
return cloned;
}
下面是一個 CloneFunction Class
[Serializable]
public abstract class CloneFunction<T>
{
public virtual T Clone()
{
T item;
MemoryStream memoryStream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memoryStream, this);
memoryStream.Position = 0;
item = (T)formatter.Deserialize(memoryStream);
return item;
}
}