[非专业翻译] Mapster - 构造函数映射

系列介绍

[非专业翻译] 是对没有中文文档进行翻译的系列博客,文章由机翻和译者自己理解构成,和原文相比有所有不同,但意思基本一致。

因个人能力有限,如有谬误之处还请指正,多多包涵。

正文

本文将说明 Mapster 如何配置构造函数映射

自定义目标对象创建

Mapster 默认实例化目标类型时,会使用目标类型的默认空构造函数实例化对象。

而使用 ConstructUsing 可以自定义实例化目标类型的实现:

// 使用非默认构造函数
TypeAdapterConfig<TSource, TDestination>.NewConfig()
    .ConstructUsing(src => new TDestination(src.Id, src.Name));

// 使用对象初始化器
TypeAdapterConfig<TSource, TDestination>.NewConfig()
    .ConstructUsing(src => new TDestination{Unmapped = "unmapped"});

映射到构造函数

Mapster 默认情况下只映射到字段和属性。可以通过 MapToConstructor 配置映射到构造函数:

// 全局
TypeAdapterConfig.GlobalSettings.Default.MapToConstructor(true);

// 特定类型
TypeAdapterConfig<Poco, Dto>.NewConfig().MapToConstructor(true);

如果想要定义自定义映射,你需要使用 Pascal case:

class Poco {
    public string Id { get; set; }
    ...
}
class Dto {
    public Dto(string code, ...) {
        ...
    }
}
TypeAdapterConfig<Poco, Dto>.NewConfig()
    .MapToConstructor(true)
    .Map('Code', 'Id'); //use Pascal case

如果一个类有多个构造函数,Mapster 将自动选择满足映射的最大数量的参数的构造函数:

class Poco {
    public int Foo { get; set; }
    public int Bar { get; set; }
}
class Dto {
    public Dto(int foo) { ... }
    public Dto(int foo, int bar) { ...} //<-- Mapster 将使用这个构造函数
    public Dto(int foo, int bar, int baz) { ... }
}

或者也可以显式地传递 ConstructorInfo 给 MapToConstructor 方法:

var ctor = typeof(Dto).GetConstructor(new[] { typeof(int), typeof(int) });
TypeAdapterConfig<Poco, Dto>.NewConfig()
    .MapToConstructor(ctor);
内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/staneee/p/14913680.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程