之前,在项目中看到过一段通用列表类型转换的代码,直接的实现便是用反射。大概看了下,它用在领域模型转DTO和SOA接口中契约实体的转换等等。首先,它使用了反射,其次,还是在循环中使用,便有了优化的想法。
方法原型如:public static List<TResult> ConvertList<TSource, TResult>(List<TSource> source) where TResult : new(),下面贴出代码。说明一下,在此我没有任何的贬义,这段代码可能比较老,其次在项目中,首先是实现功能,如果当时没有更好的实现,就先实现功能,后面有时间可以在优化,毕竟项目有时间节点,个人自己平衡哈。
public class ObjectConvertHelperOld { /// <summary> /// 转换单个对象为另外一种类型对象 /// </summary> /// <typeparam name="TSource">待转换的源对象类型</typeparam> /// <typeparam name="TResult">转换的目标对象类型</typeparam> /// <param name="source">待转换的源对象</param> /// <returns>转换的目标对象</returns> public static TResult ConvertObject<TSource, TResult>(TSource source) where TResult : new() { TResult result = new TResult(); Type sourceType = source.GetType(); Type resultType = result.GetType(); PropertyInfo[] resultProperties = resultType.GetProperties( BindingFlags.Public | BindingFlags.Instance); if (resultProperties != null && resultProperties.Length > 0) { foreach (PropertyInfo resultProperty in resultProperties) { if (resultProperty.PropertyType.IsGenericType) { continue; } PropertyInfo sourceProperty = sourceType.GetProperty(resultProperty.Name); bool isMatched = sourceProperty != null && (!sourceProperty.PropertyType.IsGenericType) && (sourceProperty.PropertyType == resultProperty.PropertyType); if (isMatched) { object currentValue = sourceProperty.GetValue(source, null); resultProperty.SetValue(result, currentValue, null); } } } return result; } /// <summary> /// 转换列表对象为另外一种列表对象 /// </summary> /// <typeparam name="TSource">待转换的源对象类型</typeparam> /// <typeparam name="TResult">转换的目标对象类型</typeparam> /// <param name="source">待转换的源对象</param> /// <returns>转换的目标对象</returns> public static List<TResult> ConvertList<TSource, TResult>(List<TSource> source) where TResult : new() { return source.ConvertAll<TResult>(ConvertObject<TSource, TResult>); } }