public class ModelToDTO { /// <summary> /// 根据模型对象获取扁平类对象 /// </summary> /// <typeparam name="S">模型类</typeparam> /// <typeparam name="T">传输类</typeparam> /// <param name="s">模型类对象</param> /// <param name="t">传输类对象</param> /// <returns></returns> public static T GetDTOModel<S, T>(S s, T t) { if (s != null) { AutoMapping<S, T>(s, t); return t; } else { return default(T); } } /// <summary> /// 实体属性反射 /// </summary> /// <typeparam name="S">赋值对象</typeparam> /// <typeparam name="T">被赋值对象</typeparam> /// <param name="s"></param> /// <param name="t"></param> private static void AutoMapping<S, T>(S s, T t) { PropertyInfo[] pps = GetPropertyInfos(s.GetType()); Type target = t.GetType(); foreach (var pp in pps) { PropertyInfo targetPP = target.GetProperty(pp.Name); object value = pp.GetValue(s, null); if (targetPP != null && value != null) { targetPP.SetValue(t, value, null); } } } //获取对象属性 private static PropertyInfo[] GetPropertyInfos(Type type) { return type.GetProperties(BindingFlags.Public | BindingFlags.Instance); } }