美文网首页
C# 两个实体类 相同属性 赋值

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

作者: Munan_ | 来源:发表于2020-04-30 16:08 被阅读0次
            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需要完善

    相关文章

      网友评论

          本文标题:C# 两个实体类 相同属性 赋值

          本文链接:https://www.haomeiwen.com/subject/vgxtghtx.html