123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- using System.Text;
- namespace Utils
- {
- /// <summary>
- /// 转换实体类
- /// </summary>
- public class ConvertHelper
- {
- /// <summary>
- /// list实体转换
- /// </summary>
- /// <typeparam name="T1"></typeparam>
- /// <typeparam name="T2"></typeparam>
- /// <param name="source"></param>
- /// <returns></returns>
- public static List<T2> ConvertToList<T1, T2>(List<T1> source)
- {
- List<T2> t2List = new List<T2>();
- if (source == null || source.Count == 0)
- return t2List;
- T2 model = default(T2);
- PropertyInfo[] pi = typeof(T2).GetProperties();
- PropertyInfo[] pi1 = typeof(T1).GetProperties();
- foreach (T1 t1Model in source)
- {
- model = Activator.CreateInstance<T2>();
- foreach (var p in pi)
- {
- foreach (var p1 in pi1)
- {
- if (p.Name == p1.Name)
- {
- p.SetValue(model, p1.GetValue(t1Model, null), null);
- break;
- }
- }
- }
- t2List.Add(model);
- }
- return t2List;
- }
- /// <summary>
- /// entity实体转换
- /// </summary>
- /// <typeparam name="T1"></typeparam>
- /// <typeparam name="T2"></typeparam>
- /// <param name="source"></param>
- /// <returns></returns>
- public static T2 ConvertToModel<T1, T2>(T1 source)
- {
- T2 model = default(T2);
- PropertyInfo[] pi = typeof(T2).GetProperties();
- PropertyInfo[] pi1 = typeof(T1).GetProperties();
- model = Activator.CreateInstance<T2>();
- foreach (var p in pi)
- {
- foreach (var p1 in pi1)
- {
- if (p.Name == p1.Name)
- {
- p.SetValue(model, p1.GetValue(source, null), null);
- break;
- }
- }
- }
- return model;
- }
- }
- }
|