之前在做DTO转换时,用到AutoMapper。但DTO的层次太深了,无奈官方没针对嵌套类型提供好的解决方案,于是自己实现了一下:
思路:采用递归和反射很好的避免手工创建嵌套对象的映射。
第一个版本,已经提交到:https://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings
代码如下 | 复制代码 |
/// /// 递归创建类型间的映射关系 (Recursively create mappings between types) ///created by cqwang /// /// /// public static void CreateNestedMappers(Type sourceType, Type destinationType) { PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance); PropertyInfo[] destinationProperties = destinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var destinationProperty in destinationProperties) { Type destinationPropertyType = destinationProperty.PropertyType; if (Filter(destinationPropertyType)) continue; PropertyInfo sourceProperty = sourceProperties.FirstOrDefault(prop => NameMatches(prop.Name, destinationProperty.Name)); if (sourceProperty == null) continue; Type sourcePropertyType=sourceProperty.PropertyType; if (destinationPropertyType.IsGenericType) { Type destinationGenericType = destinationPropertyType.GetGenericArguments()[0]; if (Filter(destinationGenericType)) continue; Type sourceGenericType = sourcePropertyType.GetGenericArguments()[0]; CreateMappers(sourceGenericType, destinationGenericType); } else { CreateMappers(sourcePropertyType, destinationPropertyType); } } Mapper.CreateMap(sourceType, destinationType); } /// /// 过滤 (Filter) /// /// /// static bool Filter(Type type) { return type.IsPrimitive || NoPrimitiveTypes.Contains(type.Name); } static readonly HashSet private static bool NameMatches(string memberName, string nameToMatch) { return String.Compare(memberName, nameToMatch, StringComparison.OrdinalIgnoreCase) == 0; } |
后来自测中发现,要过滤的一些结构体可能很多,比较麻烦,所以自己又完善了下,有了第二个版本
第二个版本在公司内的一些服务中已经使用并上线,挺好。因为并未涉及到公司内的任何业务信息,只是简单的思路和实现,所以这里贴出来给大家分享一下。
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔