You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AutoMapper的ConvertUsing映射null字符串时自定义逻辑未执行问题

AutoMapper处理Null字符串到枚举映射时自定义转换器未执行

我正在使用AutoMapper的ConvertUsing(Func<TSource, TDestination, TDestination>)方法实现字符串到枚举的映射。但发现当调用mapper.Map<InternalDeliveryType>(string source)时,如果source为null,自定义的映射函数不会执行,结果直接返回枚举的默认值。

完整代码示例如下:

var mapperCfg = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<string, InternalDeliveryType>()
    .ConvertUsing((s, d) =>
    {
        return s switch
        {
            null => InternalDeliveryType.Electronic,
            ExternalDeliveryType.Electronic => InternalDeliveryType.Electronic,
            ExternalDeliveryType.Paper => InternalDeliveryType.Paper,

            _ => throw new NotImplementedException($"Mapping '{s}' to {nameof(InternalDeliveryType)}.")
        };
    });
});

var mapper = mapperCfg.CreateMapper();

string? externalDeliveryType = null; // 从外部API传入
var internalDeliveryType = mapper.Map<InternalDeliveryType>(externalDeliveryType);
Debug.Assert(internalDeliveryType == InternalDeliveryType.Electronic);

内容的提问来源于Stack Exchange,提问作者Craig Boland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 07:52:05