• c# 反射实现模型深拷贝


    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;
            }
  • 相关阅读:
    SQL 脚本 重复执行 约束
    xiami 精选集
    PHP 5 环境配置
    Thread线程类
    创建线程
    C#中简单的正则表达式(也经常会用到的)
    线程的挂起与恢复
    C#操作INI文件
    多线程简介
    单线程简介
  • 原文地址:https://www.cnblogs.com/yijiayi/p/9695626.html
Copyright © 2020-2023  润新知