• c#深拷贝的一个方法


    使用ef,有时候会遇到,要对一个对象进行拷贝复制,可是一般的方法,拷贝后会提示此对象的实例在上下文的 entitystate已经存在,就需要用一种拷贝。
    简单的拷贝只拷贝了值类型,对引用类型的拷贝需要使用递归,依次循环到底。
    public object Copy(object obj) {             Object targetDeepCopyObj;             try {                 Type targetType = obj.GetType();                 //值类型                   if (targetType.IsValueType == true) {                     targetDeepCopyObj = obj;                 }                     //引用类型                    else {                     targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象                        System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();                     foreach (System.Reflection.MemberInfo member in memberCollection) {                         if (member.MemberType == System.Reflection.MemberTypes.Field) {                             System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;                             Object fieldValue = field.GetValue(obj);                             if (fieldValue is ICloneable) {                                 field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());                             } else {                                 field.SetValue(targetDeepCopyObj, Copy(fieldValue));                             }                         } else if (member.MemberType == System.Reflection.MemberTypes.Property) {                             System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;                             MethodInfo info = myProperty.GetSetMethod(false);                             if (info != null) {                                 object propertyValue = myProperty.GetValue(obj, null);                                 if (propertyValue is ICloneable) {                                     myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);                                 } else {                                     myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);                                 }                             }                         }                     }                 }                 return targetDeepCopyObj;             } catch (Exception e) {             }             return null;         }
  • 相关阅读:
    [archlinux][plasma][screensaver] plasma5配置屏保程序,没成功(-_-#)
    [skill][https][ssl/tls] HTTPS相关知识汇总
    [dpdk][kernel][driver] 如何让DPDK的UIO开机自动加载到正确的网卡上
    [archlinux] linux boot process/order/stage
    [potatos][flex][TBC] 语义分析词法分析 flex
    [daily][tcpdump][bpf] 如何用tcpdump抓到一个分片包
    [daily][dpdk] 网卡offload识别包类型;如何模拟环境构造一个vlan包
    [skill][c] *(char**)
    [apr] Apache Portable Runtime
    [skill] mmap / fwrite / write linux磁盘读写的分层结构
  • 原文地址:https://www.cnblogs.com/hualiu0/p/4546316.html
Copyright © 2020-2023  润新知