zoukankan      html  css  js  c++  java
  • C# 对象间的 深拷贝 实现

        以下的这个类实现了 2个含有部分字段名字相同 的对象的 赋值拷贝。


    public class ShallowCopyHelper
        {
            public static void CopyPropertiesValue(object objFrom, object objTo)
            {
                if (null == objFrom)
                {
                    return;
                }

                if (null == objTo)
                {
                    return;
                }

                Type typeFrom = objFrom.GetType();
                Type typeTo = objTo.GetType();

                if (objFrom is IList)
                {
                    try
                    {
                        int count = (objFrom as IList).Count;
                        for (int i = 0; i < count; i++)
                        {
                            CopyPropertiesValue((objFrom as IList)[i], (objTo as IList)[i]);
                        }
                    }
                    catch
                    {
                        //
                    }
                }
                else
                {
                    foreach (System.Reflection.PropertyInfo pi in
                        typeFrom.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
                    {
                        try
                        {
                            object valueFrom = typeFrom.GetProperty(pi.Name).GetValue(objFrom, null);
                            object valueTo = typeTo.GetProperty(pi.Name).GetValue(objTo, null);

                            if (typeFrom.GetProperty(pi.Name).PropertyType.IsClass
                                && !typeFrom.GetProperty(pi.Name).PropertyType.IsPrimitive
                                && !(valueFrom is String))
                            {
                                CopyPropertiesValue(valueFrom, valueTo);
                            }
                            else
                            {
                                if (valueFrom == null || !valueFrom.Equals(valueTo))
                                {
                                    //Set value to latest data
                                    typeTo.GetProperty(pi.Name).SetValue(objTo, valueFrom, null);
                                }
                            }
                        }
                        catch
                        {
                            //
                        }

                    }
                }
            }
        }
  • 相关阅读:
    关于Servelet在Tomcat中执行的原理
    类变量被final修饰编译时结果确定变为宏
    本地无法连接远程服务器(Host is not allowed to connect to this MySQL server)解决办法(Windows)
    leetcode_227. 基本计算器 II
    leetcode_150. 逆波兰表达式求值
    leetcode_145. 二叉树的后序遍历
    leetcode_144. 二叉树的前序遍历
    leetcode_94. 二叉树的中序遍历
    leetcode_71. 简化路径
    1598. 文件夹操作日志搜集器
  • 原文地址:https://www.cnblogs.com/muzizongheng/p/3169138.html
Copyright © 2011-2022 走看看