博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Clone方法

Posted on 2011-01-31 00:31  ☆Keep★Moving☆  阅读(146)  评论(0编辑  收藏  举报

/// <summary>
        /// Clone Object
        /// </summary>
        /// <returns></returns>
        public static T Clone<T>(T obj)
        {

            T cloned = default(T);
            var serializer = new DataContractSerializer(typeof(T));
            using (var ms = new MemoryStream())  
            {   
                serializer.WriteObject(ms, obj);  
                ms.Position = 0;  
                cloned = (T)serializer.ReadObject(ms);  
            }  
            return cloned;

        }

 

 

 

 

下面是一個 ‍CloneFunction Class

 

‍[Serializable]
    public abstract class CloneFunction<T>
    {
        public virtual T Clone()
        {

            T item;

            MemoryStream memoryStream = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(memoryStream, this);

            memoryStream.Position = 0;

            item = (T)formatter.Deserialize(memoryStream);

            return item;
       
        }
    }