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 EPAModelNameSpace
|
{
|
public static class DeepCopyClass
|
{
|
public static T DeepCopyByBin<T>(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;
|
}
|
private static T CloneModel<T>(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");
|
}
|
}
|
}
|