using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Xml.Serialization; namespace CommonSD
{
public class DeepCopyHelper
{
// 用一个字典来存放每个对象的反射次数来避免反射代码的循环递归
static readonly Dictionary<Type, int> TypereflectionCountDic = new Dictionary<Type, int>();
//static object _deepCopyDemoClasstypeRef = null;
// 利用反射实现深拷贝
public static T DeepCopyWithReflection<T>(T obj)
{
Type type = obj.GetType();
// 如果是字符串或值类型则直接返回
if (obj is string || type.IsValueType) return obj;
if (type.IsArray)
{
if (type.FullName != null)
{
Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
var array = obj as Array;
if (array != null)
{
Array copied = Array.CreateInstance(elementType ?? throw new InvalidOperationException(), array.Length);
for (int i = ; i < array.Length; i++)
{
copied.SetValue(DeepCopyWithReflection(array.GetValue(i)), i);
}
return (T) Convert.ChangeType(copied, obj.GetType());
}
}
} object retval = Activator.CreateInstance(obj.GetType()); PropertyInfo[] properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.Static);
foreach (var property in properties)
{
var propertyValue = property.GetValue(obj, null);
if (propertyValue == null)
continue;
property.SetValue(retval, DeepCopyWithReflection(propertyValue), null);
}
return (T) retval;
} public static T DeepCopyWithReflection_Second<T>(T obj)
{
Type type = obj.GetType(); // 如果是字符串或值类型则直接返回
if (obj is string || type.IsValueType) return obj;
if (type.IsArray)
{
if (type.FullName != null)
{
Type elementType = Type.GetType(type.FullName.Replace("[]", string.Empty));
var array = obj as Array;
if (array != null)
{
Array copied = Array.CreateInstance(elementType ?? throw new InvalidOperationException(), array.Length);
for (int i = ; i < array.Length; i++)
{
copied.SetValue(DeepCopyWithReflection_Second(array.GetValue(i)), i);
}
return (T) Convert.ChangeType(copied, obj.GetType());
}
}
} // 对于类类型开始记录对象反射的次数
int reflectionCount = Add(TypereflectionCountDic, obj.GetType());
if (reflectionCount > )
return obj; object retval = Activator.CreateInstance(obj.GetType()); PropertyInfo[] properties = obj.GetType().GetProperties(
BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.Static);
foreach (var property in properties)
{
var propertyValue = property.GetValue(obj, null);
if (propertyValue == null)
continue;
property.SetValue(retval, DeepCopyWithReflection_Second(propertyValue), null);
}
return (T) retval;
} //public static T DeepCopyWithReflection_Third<T>(T obj)
//{
// Type type = obj.GetType();
// // 如果是字符串或值类型则直接返回
// if (obj is string || type.IsValueType) return obj;
// 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(DeepCopyWithReflection_Second(array.GetValue(i)), i);
// }
// return (T) Convert.ChangeType(copied, obj.GetType());
// }
// int reflectionCount = Add(typereflectionCountDic, obj.GetType());
// if (reflectionCount > 1 && obj.GetType() == typeof(DeepCopyDemoClass))
// return (T) DeepCopyDemoClasstypeRef; // 返回deepCopyClassB对象
// object retval = Activator.CreateInstance(obj.GetType());
// if (retval.GetType() == typeof(DeepCopyDemoClass))
// DeepCopyDemoClasstypeRef = retval; // 保存一开始创建的DeepCopyDemoClass对象
// PropertyInfo[] properties = obj.GetType().GetProperties(
// BindingFlags.Public | BindingFlags.NonPublic
// | BindingFlags.Instance | BindingFlags.Static);
// foreach (var property in properties)
// {
// var propertyValue = property.GetValue(obj, null);
// if (propertyValue == null)
// continue;
// property.SetValue(retval, DeepCopyWithReflection_Third(propertyValue), null);
// }
// return (T) retval;
//} //private static T SetArrayObject<T>(T arrayObj)
//{
// Type elementType = Type.GetType(arrayObj.GetType().FullName.Replace("[]", string.Empty));
// var array = arrayObj as Array;
// Array copied = Array.CreateInstance(elementType, array.Length);
// for (int i = 0; i < array.Length; i++)
// {
// copied.SetValue(DeepCopyWithReflection_Third(array.GetValue(i)), i);
// }
// return (T) Convert.ChangeType(copied, arrayObj.GetType());
//} private static int Add(Dictionary<Type, int> dict, Type key)
{
if (key == typeof(string) || key.IsValueType) return ;
if (!dict.ContainsKey(key))
{
dict.Add(key, );
return dict[key];
}
dict[key] += ;
return dict[key];
} // 利用XML序列化和反序列化实现
public static T DeepCopyWithXmlSerializer<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
XmlSerializer xml = new XmlSerializer(typeof(T));
xml.Serialize(ms, obj);
ms.Seek(, SeekOrigin.Begin);
retval = xml.Deserialize(ms);
ms.Close();
}
return (T) retval;
} // 利用二进制序列化和反序列实现(亲测有用)
public static T DeepCopyWithBinarySerialize<T>(T obj)
{
object retval;
using (MemoryStream ms = new MemoryStream())
{
BinaryFormatter bf = new BinaryFormatter();
// 序列化成流
bf.Serialize(ms, obj);
ms.Seek(, SeekOrigin.Begin);
// 反序列化成对象
retval = bf.Deserialize(ms);
ms.Close();
}
return (T) retval;
} // 利用DataContractSerializer序列化和反序列化实现
//public static T DeepCopy<T>(T obj)
//{
// object retval;
// using (MemoryStream ms = new MemoryStream())
// {
// DataContractSerializer ser = new DataContractSerializer(typeof(T));
// ser.WriteObject(ms, obj);
// ms.Seek(0, SeekOrigin.Begin);
// retval = ser.ReadObject(ms);
// ms.Close();
// }
// return (T) retval;
//}
// 表达式树实现
// ....
public static class TransExpV2<TIn, TOut>
{
private static readonly Func<TIn, TOut> cache = GetFunc();
private static Func<TIn, TOut> GetFunc()
{
ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
List<MemberBinding> memberBindingList = new List<MemberBinding>(); foreach (var item in typeof(TOut).GetProperties())
{
if (!item.CanWrite)
continue; MemberExpression property =
Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name)); MemberBinding memberBinding = Expression.Bind(item, property);
memberBindingList.Add(memberBinding);
}
MemberInitExpression memberInitExpression =
Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray()); Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression,
new ParameterExpression[] {parameterExpression});
return lambda.Compile();
} public static TOut Trans(TIn tIn)
{
return cache(tIn);
}
}
}
}

C# 引用类型的深度拷贝帮助类的更多相关文章

  1. String 类的实现(2)深度拷贝详解

    我们已经知道了浅拷贝存在的问题,即多次析构同一空间.这个问题是类的成员函数引起的,就是前面浅拷贝里相当于编译器自动合成的函数,确切的说,浅拷贝里的问题是由隐士拷贝构造函数和隐士赋值运算符引起的. 拷贝 ...

  2. C#深度拷贝和浅度拷贝方法

    C#浅度拷贝多用于值类型的复制,即 int a=1;int b=a; 设置b=2后不会影响a的值. 但如果对于引用类型class a=new class(); class b=a; 设置b.name= ...

  3. 【转】Java如何克隆集合——深度拷贝ArrayList和HashSet

    原文网址:http://blog.csdn.net/cool_sti/article/details/21658521 原英文链接:http://javarevisited.blogspot.hk/2 ...

  4. java 深度拷贝 复制 深度复制

    1.深度拷贝.复制代码实现 最近需要用到比较两个对象属性的变化,其中一个是oldObj,另外一个是newObj,oldObj是newObj的前一个状态,所以需要在newObj的某个状态时,复制一个一样 ...

  5. C++ 默认拷贝构造函数 深度拷贝和浅拷贝

    C++类默认拷贝构造函数的弊端 C++类的中有两个特殊的构造函数,(1)无参构造函数,(2)拷贝构造函数.它们的特殊之处在于: (1) 当类中没有定义任何构造函数时,编译器会默认提供一个无参构造函数且 ...

  6. c#:如何处理对对象进行深度拷贝

    /// <summary> /// 对对象进行深度拷贝 /// </summary> /// <param name="obj"></pa ...

  7. JS 深度拷贝 Object Array

    JS 深度拷贝 Object Array function cloneObj(o) { var isArray = o instanceof Array; var isObject = o insta ...

  8. lua实现深度拷贝table表

    lua当变量作为函数的参数进行传递时,类似的也是boolean,string,number类型的变量进行值传递.而table,function,userdata类型的变量进行引用传递.故而当table ...

  9. [性能] Bean拷贝工具类性能比较

    Bean拷贝工具类性能比较 引言 几年前做过一个项目,接入新的api接口.为了和api实现解耦,决定将api返回的实体类在本地也建一个.这样做有两个好处 可以在api变更字段的时候保持应用稳定性 可以 ...

随机推荐

  1. Express 中配置使用 art-template模板引擎

    art-template 官网 https://aui.github.io/art-template/ 安装: npm install --save art-template npm install ...

  2. hadoop HA架构

    什么是Hadoop? http://hadoop.apache.org/ 解决问题:·海量数据的存储 (HDFS)·海量数据的分析 (MapReduce)·资源管理调度 (YARN) 集群规划:(这里 ...

  3. uniq 去除重复行

    1.命令功能 uniq可以输出或忽略文件中的重复行,经常需要使用sort先对文件进行排序,然后使用uniq去重并计数. 2.语法格式 uniq  option  input uniq   选项    ...

  4. java判断回文数

  5. 转Serial,Parallel,CMS,G1四大GC收集器特点小结

    转 https://blog.csdn.net/u013812939/article/details/48782343 1.Serial收集器 一个单线程的收集器,在进行垃圾收集时候,必须暂停其他所有 ...

  6. python学习笔记(七)模块

    一个python文件就是一个模块 1.标准模块 python自带的,不需要你安装的 2.第三方模块 需要安装,别人提供的,例:pip install radis 如果提示没有pip,把python下s ...

  7. ht-4 hashmap特性

    一.hashmap底层原理: hashmap调用默认构造方法会产生一个默认底层是长度为16的Entry数组,首先调用key的hasCode()方法来得到一个整数, int hash = hash(ke ...

  8. 对拍 & 随机数生成

    用 Windows 批处理对拍: 1. 新建一个批处理(.bat),代码如下: :loop@echo off data_creator.exe force_solution.exe correct_s ...

  9. HDU4035 Maze (概率DP)

    转:https://www.cnblogs.com/kuangbin/archive/2012/10/03/2711108.html 题意: 有n个房间,由n-1条隧道连通起来,实际上就形成了一棵树, ...

  10. 获取系统的documents路径

    获取路径 https://superuser.com/questions/1132288/windows-command-prompt-get-relocated-users-documents-fo ...