• 关于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);

  • 相关阅读:
    HDU1058Humble Numbers
    HDU1056 HangOver
    HDU1048The Hardest Problem Ever
    HDU 1028Ignatius and the Princess III(母函数简单题)
    HDU1014Uniform Generator
    HDU1013Digital Roots
    HDU1005Number Sequence(找规律)
    HDU1004 Let the Balloon Rise(map的简单用法)
    HDU1002 -A + B Problem II(大数a+b)
    Codeforces Round #363 (Div. 2)->C. Vacations
  • 原文地址:https://www.cnblogs.com/hanmolabi/p/9153466.html
Copyright © 2020-2023  润新知