深度拷贝指的是将一个引用类型 (包含该类型里的引用类型) 拷贝一份(在内存中完完全全是两个对象, 没有任何引用关系).......... 直接上代码:
- /// <summary>
- /// 对象的深度拷贝(序列化的方式)
- /// </summary>
- public static class MyDeepCopy
- {
- /// <summary>
- /// xml 序列化的方式实现深拷贝
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="t"></param>
- /// <returns></returns>
- public static T XmlDeepCopy<T>(T t)
- {
- // 创建 Xml 序列化对象
- XmlSerializer xml = new XmlSerializer(typeof(T));
- using (MemoryStream ms = new MemoryStream())// 创建内存流
- {
- // 将对象序列化到内存中
- xml.Serialize(ms, t);
- ms.Position = default;// 将内存流的位置设为 0
- return (T)xml.Deserialize(ms);// 继续反序列化
- }
- }
- /// <summary>
- /// 二进制序列化的方式进行深拷贝
- /// 确保需要拷贝的类里的所有成员已经标记为 [Serializable] 如果没有加该特性特报错
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="t"></param>
- /// <returns></returns>
- public static T BinaryDeepCopy<T>(T t)
- {
- // 创建二进制序列化对象
- BinaryFormatter bf = new BinaryFormatter();
- using (MemoryStream ms = new MemoryStream())// 创建内存流
- {
- // 将对象序列化到内存中
- bf.Serialize(ms, t);
- ms.Position = default;// 将内存流的位置设为 0
- return (T)bf.Deserialize(ms);// 继续反序列化
- }
- }
- }
- View Code
浅拷贝指的是将该类型里面的值类型拷贝, 而该类型里的引用类型不进行拷贝, 实现浅拷贝很简单, 再该类里编写一个方法, 方法内部调用自身的 MemberwiseClone()方法即可得到一个 object 类型的对象, 将它强转成当前对象返回即可, 列如:
- public class Person
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string Email { get; set; }
- public Cat Cat { get; set; }
- /// <summary>
- /// Person 类的浅拷贝
- /// </summary>
- /// <returns></returns>
- public Person QainClone()
- {
- // 调用自带的浅拷贝方法得到的是一个 objec 类型的对象, 然后强转直接返回就可以了
- return MemberwiseClone() as Person;
- }
- }
- View Code
string 是个列外
来源: http://www.bubuko.com/infodetail-2688281.html