zoukankan      html  css  js  c++  java
  • c# 深拷贝各种实现

    1:利用反射实现

      public T DeepCopy<T>(T obj)
            {
               object retval= Activator.CreateInstance(typeof(T));
                PropertyInfo[] pis = typeof(T).GetProperties();
                foreach (PropertyInfo pi in pis)
                {
                    try{pi.SetValue(retval, pi.GetValue(obj, null), null);  }
                    catch{  }
                }
                return (T)retval;
            }

    2:利用xml序列化和反序列化实现

       public T DeepCopy<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;
            }

    3:利用二进制序列化和反序列化实现

    public static T DeepCopy<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;
    }
     
    4:利用silverlight DataContractSerializer实现,用于在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;
    }
  • 相关阅读:
    小程序接入第三方ui库(组件库)
    element ui表格的校验和自定义校验规则
    element ui表格 表头的的特殊处理(换行/jsx风格表头)以及上传组件的一点小问题
    MongoDB 配置本地服务
    乙方渗透测试之Fuzz爆破
    SSRF漏洞挖掘经验
    SQL注入绕过技巧总结
    Xss Bypass备忘录
    bilibili存储型xss (绕过长度限制打乱顺序限制)
    XSS攻击常识及常见的XSS攻击脚本汇总
  • 原文地址:https://www.cnblogs.com/zxktxj/p/2486776.html
Copyright © 2011-2022 走看看