码迷,mamicode.com
首页 > Windows程序 > 详细

c# 反射实现模型深拷贝

时间:2018-10-19 02:24:40      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:activator   color   turn   字段   object   default   杂类   typeof   dict   

1.支持属性,不支持字段,支持复杂类型属性

2.泛型集合类支持List<T>与Dictionary<TKey,TValue>

3.如果发现有什么问题,希望大家可以多多指教

     /// <summary>
        /// 模型深拷贝
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static object Clone(this object model)
        {
            var modelType = model.GetType();
            if (modelType.IsValueType)
            {
                return model;
            }
            if (modelType.Name == typeof(List<>).Name)
            {
                var genericType = modelType.GenericTypeArguments;
                var newObj = Activator.CreateInstance(genericType.FirstOrDefault());
                var newList = (IList)Activator.CreateInstance(modelType);
                foreach (var itemObj in (IList)model)
                {
                    newList.Add(itemObj.Clone());
                }
                return newList;
            }
            if (modelType.Name == typeof(Dictionary<,>).Name)
            {
                var genericType = modelType.GenericTypeArguments;
                var newkey = Activator.CreateInstance(genericType[0]);
                var newValue = Activator.CreateInstance(genericType[1]);
                var newDic = (IDictionary)Activator.CreateInstance(modelType);
                var modelDic = (IDictionary)model;
                foreach (var itemkey in (modelDic.Keys))
                {
                    newDic.Add(itemkey.Clone(), modelDic[itemkey].Clone());

                }
                return newDic;
            }
            var pros = modelType.GetProperties();
            var newModel = Activator.CreateInstance(modelType, true);
            var newModelType = newModel.GetType();
            var newpros = newModelType.GetProperties();
            foreach (var pro in pros)
            {
                var newPro = newpros.FirstOrDefault(u => u.Name == pro.Name);
                if (pro.PropertyType.IsValueType || pro.PropertyType == typeof(string))
                {
                    var value = pro.GetValue(model);
                    newPro.SetValue(newModel, value);
                }
                else
                {
                    var value = pro.GetValue(model);
                    var actobj = Activator.CreateInstance(newPro.PropertyType, true);
                    newPro.SetValue(newModel, value.Clone());
                }
            }
            return newModel;
        }

 

c# 反射实现模型深拷贝

标签:activator   color   turn   字段   object   default   杂类   typeof   dict   

原文地址:https://www.cnblogs.com/yijiayi/p/9695626.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!