AutoMapper 用于对象映射,当源对象中包含无效类型的值时,在进行对象映射时会出现异常,为了避免这个问题,可以通过TypeConverter进行类型转换。示例如下:
public class CustomTypeConverter: ITypeConverter
return null;
}
private bool IsValidType(object source){
// 判断类型是否为有效类型
}
}
var configuration = new MapperConfiguration(cfg => {
// ...
cfg.CreateMap
var source = new Source() { Property = "some value" };
var mapper = configuration.CreateMapper();
var destination = mapper.Map
其中,IsValidType方法用于判断对象是否是有效类型,例如:
private bool IsValidType(object source) { return source is string; }
当源对象的Property属性为string类型时,对象映射可以正常进行,如果源对象中的Property属性不是string类型,CustomTypeConverter将返回null,对象映射不会报错。