using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace CommonBase { public static class DeepCopyClass { public static T DeepCopyByBin(this T obj) { object retval; using (MemoryStream ms = new MemoryStream()) { BinaryFormatter bf = new BinaryFormatter(); //序列化成流 bf.Serialize(ms, obj); ms.Seek(0, SeekOrigin.Begin); //反序列化成对象 retval = bf.Deserialize(ms); ms.Close(); } return (T)retval; } public static void SerialToFile(this object obj,string filePath) { // 创建文件流 FileStream fileStream = new FileStream(filePath, FileMode.Create); try { // 创建BinaryFormatter对象 BinaryFormatter formatter = new BinaryFormatter(); // 序列化并保存对象到文件流 formatter.Serialize(fileStream, obj); Console.WriteLine("对象已经成功序列化并保存到文件中!"); } catch (Exception ex) { Console.WriteLine("发生错误:" + ex.Message); } finally { // 关闭文件流 fileStream.Close(); } } private static T CloneModel(T oModel) { var oRes = default(T); var oType = typeof(T); //create new obj oRes = (T)Activator.CreateInstance(oType); //pass 1 property var lstPro = oType.GetProperties(); foreach (var oPro in lstPro) { var oValue = oPro.GetValue(oModel, null); oPro.SetValue(oRes, DeepCopy(oValue), null); } var lstField = oType.GetFields(); foreach (var oField in lstField) { var oValue = oField.GetValue(oModel); oField.SetValue(oRes, DeepCopy(oValue)); } return oRes; } public static object DeepCopy(this object obj) { if (obj == null) return null; Type type = obj.GetType(); if (type.IsValueType || type == typeof(string)) { return obj; } else if (type.IsArray) { Type elementType = Type.GetType( type.FullName.Replace("[]", string.Empty)); var array = obj as Array; Array copied = Array.CreateInstance(elementType, array.Length); for (int i = 0; i < array.Length; i++) { copied.SetValue(DeepCopy(array.GetValue(i)), i); } return Convert.ChangeType(copied, obj.GetType()); } else if (type.IsClass) { object toret = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); foreach (FieldInfo field in fields) { object fieldValue = field.GetValue(obj); if (fieldValue == null) continue; field.SetValue(toret, DeepCopy(fieldValue)); } return toret; } else throw new ArgumentException("Unknown type"); } } }