对象复制帮助类---DeepCopy

有的时候我们在对一个引用类型的对象进行传递操作的时候希望不要直接修改传递过来的对象,而是复制出一份来操作的时候就可以用下面的类进行复制

using System.IO;
using System.Runtime.Serialization;
using System.Collections;
using System.Collections.Generic;

namespace MED.ContactManager.View
{   
    public static class ExtensionMethods
    {
        public static T DeepCopy<T>(this T oSource,List<System.Type> knowTypes)
        {
            T oClone;            
            DataContractSerializer dcs = new DataContractSerializer(typeof(T),knowTypes);
            
            using (MemoryStream ms = new MemoryStream())
            {
                dcs.WriteObject(ms, oSource);
               
                ms.Position = 0;
                oClone = (T)dcs.ReadObject(ms);
            }           
            return oClone;
        }
        public static T DeepCopy<T>(this T oSource)
        {
            T oClone;
            DataContractSerializer dcs = new DataContractSerializer(typeof(T));

            using (MemoryStream ms = new MemoryStream())
            {
                dcs.WriteObject(ms, oSource);

                ms.Position = 0;
                oClone = (T)dcs.ReadObject(ms);
            }
            return oClone;
        }
     }
}

 

posted @ 2013-02-26 15:07  Lyghost  阅读(188)  评论(0编辑  收藏  举报