runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

 

--

 

using System;
using System.Reflection;

namespace 深拷贝N2
{
    public static class ObjectCopier
    {



        /// <summary>
        /// 使用反射
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepCopyByReflect<T>(T obj)
        {
            //如果是字符串或值类型则直接返回
            if (obj is string || obj.GetType().IsValueType) return obj;
            object retval = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); }
                catch { }
            }
            return (T)retval;
        }

        /// <summary>
        /// 跳过 List 属性字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="skipList"></param>
        /// <returns></returns>
        public static T DeepCopyByReflect<T>(T obj, bool skipList)
        {
            //如果是字符串或值类型则直接返回
            if (obj is string || obj.GetType().IsValueType) return obj;
            object retval = Activator.CreateInstance(obj.GetType());
            FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                try
                {
                    if (skipList && field.FieldType.Name.Contains("List"))
                    {
                        continue;
                    }

                    field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj), skipList));
                }
                catch { }
            }
            return (T)retval;
        }

    }
}

 

 

---

posted on 2019-09-06 20:09  runliuv  阅读(229)  评论(0编辑  收藏  举报