public static class ObjectClone
{
//聲明擴展方法
//擴展方法必須是靜態的,Add有三個參數
//this 必須有,object表示我要擴展的類型,obj表示對象名
//三個參數this和擴展的類型必不可少,對象名可以自己隨意取如果需要傳遞參數,//再增加一個變量即可
public static T Clone<T>(this object obj)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
ms.Position = 0;
return (T)(bf.Deserialize(ms)); ;
}
}
利用BinaryFormatter和MemoryStream 實現 以二進制格式序列化和反序列化對象。