C#使用反射来实现对象的深度复制的示例代码分享


本文摘自PHP中文网,作者黄舟,侵删。

下面小编就为大家带来一篇C# 使用反射来实现对象的深度复制方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

实现方式

通过挨个罗列的方式一次复制子对象是非常耗费人力的,如果子对象是引用类型,则还要需要考虑是否对子对象进一步深拷贝。

实际应用中,一个类如果有几十个子对象,挨个复制对于开发人员来说索然无味比较费时费力。

所以使用反射机制来实现。

但是如果是服务端运行的话,还是建议手动的实现。

毕竟反射机制比直接写出来的效率要慢一些。

代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

public static class DeepCopyHelper

  {

  

   public static object Copy(this object obj)

   {

     Object targetDeepCopyObj;

     Type targetType = obj.GetType();

     //值类型

     if (targetType.IsValueType == true)

     {

       targetDeepCopyObj = obj;

     }

     //引用类型

     else

     {

       targetDeepCopyObj = System.Activator.CreateInstance(targetType);  //创建引用对象

       System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();

  

       foreach (System.Reflection.MemberInfo member in memberCollection)

       {

         if (member.MemberType == System.Reflection.MemberTypes.Field)

         {

           System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;

           Object fieldValue = field.GetValue(obj);

           if (fieldValue is ICloneable)

           {

             field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());

           }

           else

           {

             field.SetValue(targetDeepCopyObj, Copy(fieldValue));

           }

  

         }

         else if (member.MemberType == System.Reflection.MemberTypes.Property)

         {

           System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;

           MethodInfo info = myProperty.GetSetMethod(false);

           if (info != null)

           {

             object propertyValue = myProperty.GetValue(obj, null);

             if (propertyValue is ICloneable)

             {

               myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);

             }

             else

             {

               myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null);

             }

           }

  

         }

       }

     }

     return targetDeepCopyObj;

   }

 }

以上就是C#使用反射来实现对象的深度复制的示例代码分享的详细内容!

相关阅读 >>

.net的优点

C#中正则表达式有什么作用?匹配字符有什么含义?

详解C#获取本机ip地址(ipv4)的代码案例

分析C#httpwebrequest访问https错误处理的方法

详解C#集合类型大盘点的图文代码

详解C#中array和arraylist的区别

C#中常用的运算符有哪些

C#thread同步mutex的代码详解

C#中如何操作word的方法示例

C#如何实现两个richtextbox控件滚动条同步滚动的简单方法

更多相关阅读请进入《C#》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...