zoukankan      html  css  js  c++  java
  • C#------如何深度克隆一个对象

    普通版:

    public static object CloneObject( object obj )
    {
      using ( MemoryStream memStream = new MemoryStream( ) )
      {
        BinaryFormatter binaryFormatter = new BinaryFormatter( null ,
          new StreamingContext( StreamingContextStates.Clone ) );
        binaryFormatter.Serialize( memStream , obj );
        memStream.Seek( 0 , SeekOrigin.Begin );
        return binaryFormatter.Deserialize( memStream );
      }
    }

    泛型版:

    public  static  T  Clone<T>(T  obj)
    {
      T  ret  =  default(T);
      if  (obj  !=  null)
      {
        XmlSerializer  cloner  =  new  XmlSerializer(typeof(T));
        MemoryStream  stream  =  new  MemoryStream();
        cloner.Serialize(stream,  obj);
        stream.Seek(0,  SeekOrigin.Begin);
        ret  =  (T)cloner.Deserialize(stream);
      }
      return  ret;
    }

    注意:如果某个类报提示错误:XXX类无法序列化,则要在类名上加上[Serializable]

    转载:

    https://blog.csdn.net/yinbucheng/article/details/62418205
  • 相关阅读:
    解决哈希(HASH)冲突的主要方法
    破解
    打工
    [JSOI2007]麻将
    [JSOI2007]建筑抢修
    [HAOI2007]上升序列
    [HAOI2007]覆盖问题
    [CQOI2017]小Q的棋盘
    [HEOI2015]兔子与樱花
    [HEOI2015]定价
  • 原文地址:https://www.cnblogs.com/tianhengblogs/p/9231896.html
Copyright © 2011-2022 走看看