C# 两个实体类 相同属性 赋值

        private static T2 CopyToModel<T1, T2>(T1 source)
        {
            T2 model = default(T2);
            PropertyInfo[] pi = typeof(T2).GetProperties();
            PropertyInfo[] pi1 = typeof(T1).GetProperties();
            model = Activator.CreateInstance<T2>();
            for (int i = 0; i < pi.Length; i++)
            {
                for (int k = 0; k < pi1.Length; k++)
                {
                    if(pi[i].Name == pi1[k].Name)
                    {
                        pi[i].SetValue(model, pi1[k].GetValue(source, null), null);
                        break;
                    }
                }
            }
            return model;
        }

        private static List<T2> CopyToList<T1, T2>(List<T1> source)
        {
            List<T2> t2List = new List<T2>();
            T2 model = default(T2);
            PropertyInfo[] pi = typeof(T2).GetProperties();
            PropertyInfo[] pi1 = typeof(T1).GetProperties();
            foreach (T1 t1Model in source)
            {
                model = Activator.CreateInstance<T2>();
                for (int i = 0; i < pi.Length; i++)
                {
                    pi[i].SetValue(model, pi1[i].GetValue(t1Model, null), null);
                }
                t2List.Add(model);
            }
            return t2List;
        }

CopyToList需要完善

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。