C#对象映射器之Mapster
简介
Mapster是一个快,小巧,功能强大的对象映射.Net框架
例子
我有两个Model类且他们的属性一致,我们将 SourceObjectTest赋值给DestObjectTest该怎么做?
SourceObjectTest sourceObject = new SourceObjectTest();
sourceObject.Name = "张三";
sourceObject.Age = new List { 20, 13, 26 };
sourceObject.Address = "XX省XX市XX县";
sourceObject.Sex = "男";
常规做法
public void Routine(SourceObjectTest sourceObject)
{
DestObjectTest destObject = new DestObjectTest();
destObject.Name = sourceObject.Name;
destObject.Sex = sourceObject.Sex;
destObject.Address = sourceObject.Address;
destObject.Age = sourceObject.Age;
}
这种类型的代码写起来相当枯燥乏味且累那么我们可不可以用第三方的库来解决这种问题呢,那肯定是可以的,像AutoMapper和Mapster就是解决这种问题的,而我为什么选择Mapster,主要还是Mapster性能更好!
安装Mapster包
使用Mapster
基本映射之映射到新对象
public void BasicMappingNewObject(SourceObjectTest sourceObject)
{
DestObjectTest destObject= sourceObject.Adapt();
}
基本映射之映射到现有对象
public void BasicMappingExistObject(SourceObjectTest sourceObject)
{
DestObjectTest destObject = new DestObjectTest();
destObject.Name = "李四";
destObject.Age = new List { 20 };
destObject.Address = "中国XX省XX市XX县";
destObject.Sex = "女";
destObject = sourceObject.Adapt(destObject);
}
自定义映射
当我们的映射对象的属性与源对象的属性不一致时我们就可以使用!eg:SourceObjectTest的name属性和DifferentDestObjectTest的UserName是一个意思,只是创建Model类的时候取得名字不一样,这时候基本映射映射不了UserName字段,那我们就要使用自定义映射了!
一:直接在 TypeAdapterConfig 配置对象的映射关系
public void BasicMappingExtend(SourceObjectTest sourceObject)
{
var config = new TypeAdapterConfig();
config.ForType()
.Map(dest => dest.UserName, src => src.Name)
.Map(dest => dest.Address, src => src.Name + src.Address);
var mapper = new Mapper(config);
DifferentDestObjectTest differentDestObjectTest = mapper.Map(sourceObject);
}
二:使用接口的方式
public class DifferentDestObjectTestRegister : IRegister
{
public void Register(TypeAdapterConfig config)
{
config.ForType()
.Map(dest => dest.UserName, src => src.Name)
.Map(dest => dest.Address, src => src.Name + src.Address);
}
}
public void BasicMappingExtend(SourceObjectTest sourceObject)
{
var config = new TypeAdapterConfig();
config.Scan(Assembly.GetExecutingAssembly());
var mapper = new Mapper(config);
DifferentDestObjectTest differentDestObjectTest = mapper.Map(sourceObject);
}
三:使用映射配置
public void MappingConfig(SourceObjectTest sourceObject)
{
TypeAdapterConfig
.NewConfig()
.Map(dest => dest.UserName,
src => src.Name);
DifferentDestObjectTest differentDestObjectTest = TypeAdapter
.Adapt(sourceObject);
}
当然还有其它功能,可前往官网!- 传送门!
最后大家如果喜欢我的文章,还麻烦给个关注并点个赞, 希望net生态圈越来越好!
评论