zoukankan      html  css  js  c++  java
  • 关于C#类的深拷贝的问题

           最近在对list进行add新元素时,发现add使用的是引用,因此在增加重复元素时,得使用深拷贝进行元素的复制。类对象的复制,一个个属性进行赋值略显笨拙,因此在网上找到了个通用的方法。比较好用,据称为表达树式https://www.cnblogs.com/emrys5/p/expression_trans_model.html

    public static class TransExpV2<TIn, TOut>
        {
    
            private static readonly Func<TIn, TOut> cache = GetFunc();
            private static Func<TIn, TOut> GetFunc()
            {
                ParameterExpression parameterExpression = Expression.Parameter(typeof(TIn), "p");
                List<MemberBinding> memberBindingList = new List<MemberBinding>();
    
                foreach (var item in typeof(TOut).GetProperties())
                {
             if (!item.CanWrite)
                  continue;
    
                    MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
    
                MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());
                Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[] { parameterExpression });
    
                return lambda.Compile();
            }
    
            public static TOut Trans(TIn tIn)
            {
                return cache(tIn);
            }
    
        }

      调用:StudentSecond ss= TransExpV2<Student, StudentSecond>.Trans(s);

  • 相关阅读:
    SHELL
    终端如何输出彩色字体
    BTree和B+Tree详解
    博客项目----小功能模块
    python的学习之旅---Mysql数据库
    Python的学习之旅———协程
    python的学习之旅---信号量 定时器
    python的学习之旅---回调机制
    Python的学习之旅———线程 事件
    centos安装redis
  • 原文地址:https://www.cnblogs.com/hanmolabi/p/9153466.html
Copyright © 2011-2022 走看看