zoukankan      html  css  js  c++  java
  • C# 深层拷贝(DeepClone)

    一、反射拷贝

     //四种深拷贝方法
    
            ///反射拷贝
            public static T DeepCopyByReflect<T>(T obj)
            {
                //如果是字符串或值类型则直接返回
                if (obj is string || obj.GetType().IsValueType) return obj;
    
                object retval = Activator.CreateInstance(obj.GetType());
                FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
                foreach (FieldInfo field in fields)
                {
                    try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); }
                    catch { }
                }
                return (T)retval;
            }
    View Code

    二、Xml拷贝

           //xml拷贝
            public static T DeepCopyByXml<T>(T obj)
            {
                object retval;
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlSerializer xml = new XmlSerializer(typeof(T));
                    xml.Serialize(ms, obj);
                    ms.Seek(0, SeekOrigin.Begin);
                    retval = xml.Deserialize(ms);
                    ms.Close();
                }
                return (T)retval;
            }
     
    View Code

    三、序列化拷贝

           //序列化拷贝
            public static T DeepCopyByBin<T>(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;
            }
    View Code

    四、silverlight

    //需要silverlight 支持
     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;
            }
    View Code
  • 相关阅读:
    帧锁定同步算法
    为 Raft 引入 leader lease 机制解决集群脑裂时的 stale read 问题
    etcd:从应用场景到实现原理的全方位解读
    给定一个二叉搜索树(BST),找到树中第 K 小的节点
    UDP如何实现可靠传输
    理解TCP/IP三次握手与四次挥手的正确姿势
    Redis持久化
    Redis提供的持久化机制(RDB和AOF)
    redis渐进式 rehash
    redis rehash
  • 原文地址:https://www.cnblogs.com/Bull-Rush/p/13320825.html
Copyright © 2011-2022 走看看