c# 反射实现模型深拷贝

时间:2021-01-06 19:57:00

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;
        }