1. 程式人生 > >.net 反射實現兩個相同結構實體類的轉換

.net 反射實現兩個相同結構實體類的轉換

兩個結構相同的實體類的轉換,T2實體類的屬性數可以大於T1的屬性數,可用於api介面實體類引數到資料庫實體的轉換。

public 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;

        }

        public 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++)

            {

                pi[i].SetValue(model, pi1[i].GetValue(source, null), null);

            }

            return model;

        }