/// <summary> /// GenerateTFromToEntity /// </summary> /// <typeparam name="TFrom">TInfo</typeparam> /// <typeparam name="TTo">TEntity</typeparam> /// <param name="fromInfo">TInfo object</param> /// <param name="toEntity">TEntity object</param> /// <returns>TEntity object</returns> public TTo GenerateTFromToEntity<TFrom, TTo>(TFrom fromInfo, TTo toEntity) { //从fromInfo中获取类形式并读取其属性构成集合 var fromProperties = fromInfo.GetType().GetProperties(); //获取目标对象toEntity的类形式并将其属性构成集合 //遍历toEntity属性集合,该属性必须为可写,即包含"set"方法 foreach(var toProperty in toEntity.GetType().GetProperties().Where(c => c.CanWrite)) { //获取在fromInfo的属性集合中与当前toEntity的属性名相同的属性 var fromProperty = fromProperties.FirstOrDefault(c => c.Name.Contains(toProperty.Name)); //如果不存在该属性,则继续遍历 if(fromProperty == null) continue; //从fromInfo中获取fromProperty属性所对应的属性值 //此处的object类可替换成更实际的引用类型,例如某个class,or string object ToValue = fromProperty.GetValue(fromInfo, null); //定义在toEntity中相应属性的属性值 object ToEntityValue = null ; //这里在TFrom中所有属性都为string,而ToEntity中则有不同类型,因此需要对获得的属性值进行属性转换 //转换方法这里只写个例子,相应转换可以自行添加,这里获得的ToValue是object型的 if(toProperty.PropertyType != typeof(string)) { if(toProperty.PropertyType == typeof(DateTime)) { ToEntityValue = Convert.ToDateTime(ToValue.ToString()); } } else { if(string.IsNullOrEmpty(ToValue.ToString())) { ToValue = null; } else { ToEntityValue = ToValue.ToString().Trim(); } } //最后将获得的ToEntityValue作为属性值, //传递给toEntity中的toProperty值 toProperty.SetValue(toEntity, ToEntityValue, null); } return toEntity; }
到这里,转换结束,转换的两个类型中的对应属性名必须一致,当然如果有略微偏差,可以通过对方法的修改来弥补。
转换完成的值都是引用类型,因此如果需要通过这个方法构成List<TEntity>,需要实现TEntity支持克隆接口,详细的在之后文章中会提到。