AutoMapper官方文档(九)【列表和数组】

来源:互联网 发布:敏感肌肤 面膜 知乎 编辑:程序博客网 时间:2024/05/24 04:09

AutoMapper只需要配置元素类型,而不是任何可能使用的数组或列表类型。 例如,我们可能有一个简单的源和目标类型:

public class Source{    public int Value { get; set; }}public class Destination{    public int Value { get; set; }}

所有基本的泛型集合类型都被支持:

Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>());var sources = new[]    {        new Source { Value = 5 },        new Source { Value = 6 },        new Source { Value = 7 }    };IEnumerable<Destination> ienumerableDest = Mapper.Map<Source[], IEnumerable<Destination>>(sources);ICollection<Destination> icollectionDest = Mapper.Map<Source[], ICollection<Destination>>(sources);IList<Destination> ilistDest = Mapper.Map<Source[], IList<Destination>>(sources);List<Destination> listDest = Mapper.Map<Source[], List<Destination>>(sources);Destination[] arrayDest = Mapper.Map<Source[], Destination[]>(sources);

具体而言,支持的源集合类型包括:

    IEnumerable    IEnumerable<T>    ICollection    ICollection<T>    IList    IList<T>    List<T>    Arrays

对于非泛型可枚举类型,仅支持未映射的可指定类型,因为AutoMapper将无法“猜测”您尝试映射的类型。 如上例所示,没有必要显式配置列表类型,只有它们的成员类型。

映射到现有集合时,首先清除目标集合。 如果这不是你想要的,看看AutoMapper.Collection

集合中的多态元素类型

很多时候,我们的源和目标类型都可能有一个类型的层次结构。 AutoMapper支持多态数组和集合,如果找到,则使用派生的源/目标类型。

public class ParentSource{    public int Value1 { get; set; }}public class ChildSource : ParentSource{    public int Value2 { get; set; }}public class ParentDestination{    public int Value1 { get; set; }}public class ChildDestination : ParentDestination{    public int Value2 { get; set; }}

AutoMapper仍然需要显式配置子映射,因为AutoMapper不能“猜测”要使用的特定子目标映射。 以下是上述类型的示例:

Mapper.Initialize(c=> {    c.CreateMap<ParentSource, ParentDestination>()         .Include<ChildSource, ChildDestination>();    c.CreateMap<ChildSource, ChildDestination>();});var sources = new[]    {        new ParentSource(),        new ChildSource(),        new ParentSource()    };var destinations = Mapper.Map<ParentSource[], ParentDestination[]>(sources);destinations[0].ShouldBeInstanceOf<ParentDestination>();destinations[1].ShouldBeInstanceOf<ChildDestination>();destinations[2].ShouldBeInstanceOf<ParentDestination>();
原创粉丝点击