Mappest操作
1 public static class MappTest 2 { 3 public static void Run() 4 { 5 var config = new TypeAdapterConfig(); 6 //只要配置需要处理的类,并支持多个属性操作 7 config.ForType<MiddleClass, MiddleClass2>() 8 .Map(dest => dest.NamesJson, src => JsonConvert.SerializeObject(src.InnermostClasses)); 9 config.ForType<MiddleClass, MiddleClass2>() 10 .Map(dest => dest.MidMyProperty, src => src.MidMyProperty-1); 11 var mapper = new Mapper(config); 12 var outerClass = new OuterClass 13 { 14 MyProperty=1, 15 MiddleClasses = new List<MiddleClass> 16 { 17 new MiddleClass 18 { 19 MidMyProperty=2, 20 InnermostClasses = new List<InnermostClass> 21 { 22 new InnermostClass 23 { 24 Names = new List<Dto> 25 { 26 new Dto { Name = "Item1" }, 27 new Dto { Name = "Item2" } 28 } 29 } 30 } 31 } 32 } 33 }; 34 var outerDto = mapper.Map<OuterDto>(outerClass); 35 } 36 public class OuterDto 37 { 38 public int MyProperty { get; set; } 39 public List<MiddleClass2> MiddleClasses { get; set; } 40 } 41 public class OuterClass 42 { 43 public int MyProperty { get; set; } 44 public List<MiddleClass> MiddleClasses { get; set; } 45 } 46 47 public class MiddleClass 48 { 49 public int MidMyProperty { get; set; } 50 public List<InnermostClass> InnermostClasses { get; set; } 51 } 52 public class MiddleClass2 53 { 54 public int MidMyProperty { get; set; } 55 public string NamesJson { get; set; } 56 } 57 58 public class InnermostClass 59 { 60 public List<Dto> Names { get; set; } 61 } 62 63 public class Dto 64 { 65 public string Name { get; set; } 66 } 67 }
调用:
MappTest.Run();
返回结果:
原创不易,转载请声明 bindot
https://www.cnblogs.com/bindot/