標籤:
.NET中對於複雜物件製作副本比較困難,閑暇之時寫了這個方法,和大家分享。
本案例用於大型物件的副本製作,常見的應用情境就是樹形對象節點的拷貝,但是也有局限性,目前使用於類裡有基本類型(int stirng float 等)的屬性和泛型屬性的拷貝,其他的拷貝暫時不支援。
1、自定Teacher類
class Teacher { public Teacher() { } /// <summary> /// 老師姓名 /// </summary> public string TeacherName { get; set; } /// <summary> /// 老師的工號 /// </summary> public string TeacherNumber { get; set; } /// <summary> /// 學生列表 /// </summary> public List<Student> lists { get; set; } }
2、學生類型定義
class Student { /// <summary> /// 學生姓名 /// </summary> public string StudentName { get; set; } public Student() { } }
3、聲明並初始設定變數
Teacher teacher = new Teacher() { TeacherNumber = "0000000001", TeacherName = "老師1", lists = new List<Student> { new Student { StudentName = "學生1" }, new Student { StudentName = "學生2" } } };
4、 對象進行副本的製造
Teacher teacherAfter = teacher.Copy();
5、Copy方法的實現
1 #region 對類進行深度拷貝 2 /// <summary> 3 /// 對類進行深度拷貝 4 /// </summary> 5 /// <typeparam name="T"></typeparam> 6 /// <param name="o"></param> 7 /// <returns></returns> 8 public static T Copy<T>(this T o) 9 {10 Assembly assembly = Assembly.GetExecutingAssembly();11 Type t = o.GetType();12 T t1 = (T)assembly.CreateInstance(t.FullName);13 14 PropertyInfo[] PropertyInfos = t.GetProperties();15 16 foreach (PropertyInfo propertyInfo in PropertyInfos)17 {18 string PropertyName = propertyInfo.Name;19 var propertyValue = propertyInfo.GetValue(o, null);20 if (propertyValue is IEnumerable<object>)21 {22 IEnumerable<object> propertyList = propertyValue as IEnumerable<object>;23 object list = Activator.CreateInstance(propertyValue.GetType());24 foreach (var item in propertyList)25 {26 var method = list.GetType().GetMethod("Add");27 method.Invoke(list, new[] { Copy<object>(item) });28 }29 propertyInfo.SetValue(t1, list, null);30 }31 else32 {33 propertyInfo.SetValue(t1, propertyValue, null);34 }35 }36 return t1;37 }38 #endregion
代碼講解
1、首先這是個拓展方法,拓展方法不懂得百度去。
2、 10行、11行、12行用於實現一個類型的執行個體化t1。
3、通過遍曆o的屬性對拷貝對象t1進行賦值,這是針對基本類型的屬性而言,對於IEnumerable就涉及到類型轉換,然後進行遍曆,遞迴調用Copy方法。
提供demo的 下載
.NET中製做對象的副本(一)