标签:成员变量 log 孙悟空 实现 序列化 客户 值类型 抽象 des
分析:
[Serializable] //深克隆时需要将类标记为Serializable public class Person:ICloneable { public string CurrentEmployee { get; set; } public Member Member { get; set; } public Person() { this.CurrentEmployee = "admin"; Member member = new Member(); member.Id = 3; member.Name = "Mem"; this.Member = member; } public object Clone() { return this.MemberwiseClone(); } #region 静态方式创建对象 private static Person _person; /// <summary> /// 静态构造函数,永远只运行一次 /// </summary> static Person() { _person = new Person(); } public static Person StaticClone() { return _person.MemberwiseClone() as Person; } #endregion }
[Serializable] public class Member { public int Id { get; set; } public string Name { get; set; } }
public class SerializeHelper { /// <summary> /// 序列化 /// </summary> /// <param name="target"></param> /// <returns></returns> public static string Serializable(object target) { using(MemoryStream stream=new MemoryStream()) { new BinaryFormatter().Serialize(stream,target); return Convert.ToBase64String(stream.ToArray()); } } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> /// <returns></returns> public static T Derializable<T>(string target) { byte[] targetArray = Convert.FromBase64String(target); using (MemoryStream stream = new MemoryStream(targetArray)) { return (T)(new BinaryFormatter().Deserialize(stream)); } } /// <summary> /// 合并反序列化与序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <returns></returns> public static T DeepClone<T>(T t) { return Derializable<T>(Serializable(t)); } }
调用:
//浅表克隆,原来创建的对象值会改变 Person p = new Person(); Person p1 = p.Clone() as Person; p1.CurrentEmployee = "user"; p1.Member.Id = 1; p1.Member.Name = "pp1"; //深度克隆,原来创建的对象值不会改变 Person p2 = p.Clone() as Person; Person p3 = SerializeHelper.Derializable<Person>(SerializeHelper.Serializable(p2)); //或者简写 //Person p3 = SerializeHelper.DeepClone<Person>(p2); p3.Member.Id = 6; p3.Member.Name = "dd3"; Console.Read();
标签:成员变量 log 孙悟空 实现 序列化 客户 值类型 抽象 des
原文地址:http://www.cnblogs.com/genesis/p/6097528.html