C# 引用类型对象在拷备时,一般有浅拷备与深拷备,浅拷备指向的是同一对象的引用地址,一个对象的修改必然会影响另一个对象,而深拷备是直接拷备对象的内容,而不是引用,拷备后的对象拥有新的引用,这里主要介绍深拷备的实现,其实现 方式有3种,好了直接上代码:
1. 首先定义一个类:
using System;
using System.IO;
namespace DemonCol
{
[Serializable] // 可序列化标记
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
public FileMode MyFileMode { get; set; }
}
}
2. 定义深拷备方法
方法1: 通过序列化与反序列化实现深拷备
需要添加的引用: using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Runtime.Serialization;
Person 类的头部必须添加标记: [Serializable]
/// <summary>
/// 通过序列化与反序列化实现深拷备
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T DeepCopyBySerialize<T>(T obj)
{
object returnObj;
using (MemoryStream ms = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
returnObj = formatter.Deserialize(ms);
ms.Close();
}
return (T)returnObj;
}
方法2: 通过 XML 序列化与反序列化实现 深拷备
需要添加的引用: using System.Xml.Serialization;
Person 类的头部可不用 标记:[Serializable]
/// <summary>
/// 通过 XML 序列化与反序列化实现 深拷备
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T DeepCopyByXmlSerialize<T>(T obj)
{
object returnObj;
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer xs = new XmlSerializer(typeof(T));
xs.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
returnObj = xs.Deserialize(ms);
ms.Close();
}
return (T)returnObj;
}
方法3: 通过 反射实现 深拷备
需要添加的引用: using System.Reflection;
Person 类的头部 可不用 标记:[Serializable]
/// <summary>
/// 通过 反射实现 深拷备
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T DeepCopyByReflection<T>(T obj)
{
if (obj is string || obj.GetType().IsValueType)
return obj;
object returnObj = Activator.CreateInstance(obj.GetType());
FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
foreach (FieldInfo item in fields)
{
try
{
item.SetValue(returnObj, DeepCopyByReflection(item.GetValue(obj)));
}
catch { }
}
return (T)returnObj;
}
3. 客户端测试
static void Main(string[] args)
{
Person person = new Person();
person.Age = 20;
person.Name = "will";
person.MyFileMode = FileMode.Create; Person person2 = person;
Person person3 = DeepCopyBySerialize<Person>(person); person.Name = "modify";
person.Age = 10;
person.MyFileMode = FileMode.Open;
Console.ReadKey();
}
运行结果: