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 实现 以二进制格式序列化和反序列化对象。