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. hadoop HA + HBase HA搭建:

    hadoop HA搭建参考:https://www.cnblogs.com/NGames/p/11083640.html (本节:用不到YARN 所以可以不用考虑部署YARN部分) Hadoop 使用 ...

  2. python使用etcd

    import sys import etcd client = etcd.Client( host='127.0.0.1', port=2379, allow_reconnect=True) clie ...

  3. macaca搭建

    对于新鲜的事务总是那么好奇,在自动化的过程中,有幸了解到macaca,记录下安装过程,具体介绍请移步官网:https://github.com/macacajs/ python版本参考:https:/ ...

  4. (arm板子tensorflow安装)armv7板子pip安装的wheel

    树莓派之类的armv7板子在,安装 numpy,scipy时经常失败,因为安装过程是下载源码包到本地编译,然后再安装的,编译过程中往往就会失败. https://www.piwheels.org/si ...

  5. CMD批处理查看当前路径

    1.直接在CMD窗口查看 echo %cd% 2.建立批处理文件 @echo offecho 当前盘符:%~d0echo 当前盘符和路径:%~dp0echo 当前批处理全路径:%~f0echo 当前盘 ...

  6. C语言的结构体的具体作用是?

    在实际问题中,一组数据往往具有不同的数据类型.例如,在学生登记表中,姓名应为字符型:学号可为整型或字符型:年龄应为整型:性别应为字符型:成绩可为整型或实型.显然不能用一个数组来存放这一组数据.因为数组 ...

  7. php strrpos()函数 语法

    php strrpos()函数 语法 作用:寻找某字符串中某字符最后出现的位置.大理石构件怎么选择 语法:strrpos(string,find,start) 参数: 参数 描述 string 必需. ...

  8. HTML计算机代码元素

    计算机代码 1 2 3 4 5 6 var person = {     firstName:"Bill",     lastName:"Gates",     ...

  9. spring-cloud zuul网关

    API Gateway 是随着微服务(Microservice)这个概念一起兴起的一种架构模式,它用于解决微服务过于分散,没有一个统一的出入口进行流量管理的问题. 使用 Zuul 实现 API Gat ...

  10. ag-grid 表格中添加图片

    ag-grid是一种非常好用的表格,网上搜索会有各种各样的基本用法,不过对于在ag-grid 表格中添加图片我没有找到方法,看了官方的文档,当然英文的自己也是靠网页翻译,最后发现有这么一个例子,我知道 ...