c# 实体类的克隆(复制)

实体类直接new对象,是无法克隆出一个同样的类的,只要把新的class改了,就的class也会改变,接下来有两种真正克隆类的办法,基本上可以解决大部分的问题。

1、用反射

       Student ss = TransReflection<Student, Student>(stu);

        private static TOut TransReflection<TIn, TOut>(TIn tIn)
        {
            TOut tOut = Activator.CreateInstance<TOut>();
            var tInType = tIn.GetType();
            foreach (var itemOut in tOut.GetType().GetProperties())
            {
                var itemIn = tInType.GetProperty(itemOut.Name); ;
                if (itemIn != null)
                {
                    itemOut.SetValue(tOut, itemIn.GetValue(tIn));
                }
            }
            return tOut;
        }

2、用序列化

   Student sss = JsonConvert.DeserializeObject<Student>(JsonConvert.SerializeObject(stu));