前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >记录一次数据复制帮助方法

记录一次数据复制帮助方法

作者头像
await
发布2022-12-07 14:34:52
1820
发布2022-12-07 14:34:52
举报
文章被收录于专栏:awaitawait

为解决 两个对象,object1,object2 怎么样将object1中的值赋给object2, 而且,赋值后,改变object1的值,object2的值不变 记录为解决多个对象都指向同一个内存地址而导致数据错乱问题

写了个帮助方法

代码语言:javascript
复制
 public class CopyDataHelper
    {
        /// 
        /// 复制数据
        /// 
        /// 
        /// 
        /// 
        public static void CopyData(T source, T target)
        {
            var sourceType = source.GetType();
            var targetType = target.GetType();
            var sourceProperties = sourceType.GetProperties();
            var targetProperties = targetType.GetProperties();
            foreach (var sourceProperty in sourceProperties)
            {
                foreach (var targetProperty in targetProperties)
                {
                    if (sourceProperty.Name == targetProperty.Name)
                    {
                        targetProperty.SetValue(target, sourceProperty.GetValue(source));
                    }
                }
            }
        }
        /// 
        /// 复制对象
        /// 
        /// 
        /// 
        /// 
        public static T Copy(T source)
        {
            if (source == null)
            {
                return default(T);
            }

            return (T)Copy(source, typeof(T));
        }

        /// 
        /// 复制对象
        /// 
        /// 
        /// 
        /// 
        public static object Copy(object source, Type type)
        {
            if (source == null)
            {
                return null;
            }

            var obj = Activator.CreateInstance(type);
            var properties = type.GetProperties();
            foreach (var property in properties)
            {
                var value = property.GetValue(source);
                property.SetValue(obj, value);
            }

            return obj;
        }
        
        /// 
        /// 深拷贝
        /// 
        /// 
        /// 
        /// 
        public static T DeepCopy(T obj)
        {
            if (obj == null)
            {
                return default(T);
            }
            using (var ms = new System.IO.MemoryStream())
            {
                var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(ms, obj);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                return (T)formatter.Deserialize(ms);
            }
        }

    }

本文共 79 个字数,平均阅读时长 ≈ 1分钟

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档