.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 = "",
TeacherName = "老师1",
lists = new List<Student>
{
new Student { StudentName = "学生1" },
new Student { StudentName = "学生2" }
}
};

4、 对象进行副本的制造

 Teacher teacherAfter = teacher.Copy();

5、Copy方法的实现

   #region 对类进行深度拷贝
/// <summary>
/// 对类进行深度拷贝
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="o"></param>
/// <returns></returns>
public static T Copy<T>(this T o)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type t = o.GetType();
T t1 = (T)assembly.CreateInstance(t.FullName); PropertyInfo[] PropertyInfos = t.GetProperties(); foreach (PropertyInfo propertyInfo in PropertyInfos)
{
string PropertyName = propertyInfo.Name;
var propertyValue = propertyInfo.GetValue(o, null);
if (propertyValue is IEnumerable<object>)
{
IEnumerable<object> propertyList = propertyValue as IEnumerable<object>;
object list = Activator.CreateInstance(propertyValue.GetType());
foreach (var item in propertyList)
{
var method = list.GetType().GetMethod("Add");
method.Invoke(list, new[] { Copy<object>(item) });
}
propertyInfo.SetValue(t1, list, null);
}
else
{
propertyInfo.SetValue(t1, propertyValue, null);
}
}
return t1;
}
#endregion

代码讲解

1、首先这是个拓展方法,拓展方法不懂得百度去。

2、 10行、11行、12行用于实现一个类型的实例化t1。

3、通过遍历o的属性对拷贝对象t1进行赋值,这是针对基本类型的属性而言,对于IEnumerable就涉及到类型转换,然后进行遍历,递归调用Copy方法。

提供demo的下载地址 下载

最新文章

  1. css3几个新属性
  2. backprop示例
  3. silverlight 获取服务器上图片出现异常 “AG_E_NETWORK_ERROR”
  4. [模拟]ZOJ3485 Identification Number
  5. [HDU 1520] Anniversary party
  6. Android开发系列之button事件的4种写法
  7. Office 2010
  8. IP地址分类与识别错误
  9. Glide的常用方法注释
  10. iOS开发——应用图标上显示消息数量
  11. Dinic算法(研究总结,网络流)
  12. python的学习笔记01_3 基本运算符 流程控制if while 字符串常用办法
  13. openssh-win64 on windows2016 ssh pub key config
  14. python面向对象学习(一)基本概念
  15. MyBatis - 5.缓存机制
  16. 在Pandas中更改列的数据类型【方法总结】
  17. 腾讯、百度、网易游戏、华为Offer及笔经面经
  18. Anaconda完全入门指南
  19. 转:3d max 2013 安装教程,凭着一种互联网精神提供给广大朋友
  20. MYSQL常见的可优化点

热门文章

  1. MK-编辑器
  2. saltstack grains
  3. TensorFlow入门学习(让机器/算法帮助我们作出选择)
  4. java io系列24之 BufferedWriter(字符缓冲输出流)
  5. TIMESTAMP使用遇到得麻烦
  6. Maven入门:使用Nexus搭建Maven私服及上传下载jar包
  7. python -- leetcode 刷题之路
  8. 微信小程序,错误{&quot;errMsg&quot;:&quot;request:fail 小程序要求的 TLS 版本必须大于等于 1.2&quot;}
  9. 061、flannel的连通与隔离(2019-04-01 周一)
  10. 自学python 2.