有基礎的開發者都應該很明白,對象是一個引用類型,例如:算法
object b=new object();this
object a=b;spa
那麼a指向的是b的地址,這樣在有些時候就會形成若是修改a的值,那麼b的值也會跟隨着改變(a和b是同一個引用內存地址)。code
咱們想要a和b都是各自互不影響的,那麼只能是徹底地新建一個新的對象,而且把現有對象的每一個屬性的值賦給新的對象的屬性。也就是值類型的複製,這個操做就叫深度克隆。對象
這裏咱們寫兩個泛型方法分別對對象T和集合List<T>進行深度克隆的實現,咱們的方法實現方式是「擴展方法」,就是能在原有的對象後面直接「點」操做。blog
下面咱們來看一下深度克隆的算法實現:內存
using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; /** * author:qixiao * create:2017-5-25 11:52:21 * */ namespace QX_Frame.Helper_DG.Extends { public static class CloneExtends { public static T DeepCloneObject<T>(this T t) where T : class { T model = System.Activator.CreateInstance<T>(); //實例化一個T類型對象 PropertyInfo[] propertyInfos = model.GetType().GetProperties(); //獲取T對象的全部公共屬性 foreach (PropertyInfo propertyInfo in propertyInfos) { //判斷值是否爲空,若是空賦值爲null見else if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { //若是convertsionType爲nullable類,聲明一個NullableConverter類,該類提供從Nullable類到基礎基元類型的轉換 NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType); //將convertsionType轉換爲nullable對的基礎基元類型 propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(t), nullableConverter.UnderlyingType), null); } else { propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(t), propertyInfo.PropertyType), null); } } return model; } public static IList<T> DeepCloneList<T>(this IList<T> tList) where T : class { IList<T> listNew = new List<T>(); foreach (var item in tList) { T model = System.Activator.CreateInstance<T>(); //實例化一個T類型對象 PropertyInfo[] propertyInfos = model.GetType().GetProperties(); //獲取T對象的全部公共屬性 foreach (PropertyInfo propertyInfo in propertyInfos) { //判斷值是否爲空,若是空賦值爲null見else if (propertyInfo.PropertyType.IsGenericType && propertyInfo.PropertyType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { //若是convertsionType爲nullable類,聲明一個NullableConverter類,該類提供從Nullable類到基礎基元類型的轉換 NullableConverter nullableConverter = new NullableConverter(propertyInfo.PropertyType); //將convertsionType轉換爲nullable對的基礎基元類型 propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(item), nullableConverter.UnderlyingType), null); } else { propertyInfo.SetValue(model, Convert.ChangeType(propertyInfo.GetValue(item), propertyInfo.PropertyType), null); } } listNew.Add(model); } return listNew; } } }
上述代碼已經實現了深度克隆的操做,在使用上咱們以下:開發
例若有User類,咱們能夠這樣操做it
User user1=new User();io
User user2=user1.DeepCloneObject();
這樣就完成了對user1的深度克隆!