15 Jul 2009

C#中如何深度克隆一个对象?

Share

如何深度克隆一个对象?

普通版:

        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;
}

comments powered by Disqus