标签:
1 public class Sourse
2 {
3 public int A;
4 public decimal? B;
5 public string C;
6 public Inner D;
7 public string E;
8 }
9
10 public class Dest
11 {
12 public int? A;
13 public decimal B;
14 public DateTime C;
15 public Inner D;
16 public string F;
17 }
18
19 public class Inner
20 {
21 public long D1;
22 public Guid D2;
23 }
24
25 Sourse src = new Sourse
26 {
27 A = 1,
28 B = 0M,
29 C = "2011/9/21 0:00:00",
30 D = new Inner
31 {
32 D2 = Guid.NewGuid()
33 },
34 E = "test"
35 };
36
37 ObjectsMapper<Sourse, Dest> mapper =
38 ObjectMapperManager.DefaultInstance.GetMapper<Sourse, Dest>();
39 Dest dst = mapper.Map(src);
40
41 Assert.AreEqual<string>(dst.B.ToString(), src.B);
42 Assert.AreEqual<long>(dst.C.C1, 0L);
43 Assert.AreEqual<Guid>(dst.C.C2, src.C.C2);
44 Assert.IsNull(dst.E);
支持的方法 |
描述 |
ConvertUsing |
为指定的成员提供自定义的转换逻辑 |
ConvertGeneric |
为指定的泛型类型成员提供自定义的转换逻辑 |
ConstructBy |
为目标对象使用指定的构造函数替代默认构造函数 |
NullSubstitution |
当源对象中指定的成员在为null时,给目标对象的成员赋值 |
IgnoreMembers |
忽略指定成员的映射 |
PostProcess |
在映射完成后执行指定的方法 |
ShallowMap |
指定的成员采用浅拷贝方式映射 |
DeepMap |
指定的成员采用深拷贝方式映射 |
MatchMembers |
如果成员名称的映射不采用精确匹配,可以指定具体的映射逻辑 |
1 public class Sourse
2 {
3 public int A;
4 public decimal? B;
5 public string C;
6 public Inner D;
7 public string E;
8 }
9
10 public class Dest
11 {
12 public int? A;
13 public decimal B;
14 public DateTime C;
15 public Inner2 D;
16 public string F;
17 }
18
19 public class Inner
20 {
21 public long D1;
22 public Guid D2;
23 }
24
25 public class Inner2
26 {
27 public long D12;
28 public Guid D22;
29 }
30
31 ObjectsMapper<Sourse, Dest> mapper1 =
32 new ObjectMapperManager().GetMapper<Sourse, Dest>(
33 new DefaultMapConfig()
34 .IgnoreMembers<Sourse, Dest>(new string[] { "A" })
35 .NullSubstitution<decimal?, decimal>((value) => -1M)
36 .ConvertUsing<Inner, Inner2>(value => new Inner2 { D12 = value.D1, D22 = value.D2 })
37 .PostProcess<Dest>((value, state) => { value.F = "nothing"; return value; })
38 );
39 Dest dst = mapper1.Map(src);
40
41 Assert.IsNull(dst.A);
42 Assert.AreEqual<decimal>(dst.B, -1M);
43 Assert.AreEqual<Guid>(dst.D.D22, src.D.D2);
44 Assert.AreEqual<string>(dst.F, "nothing");
标签:
原文地址:http://www.cnblogs.com/james641/p/5817287.html