繁体   English   中英

如何 map 2 Enums based on name in C#?

[英]How to map 2 Enums based on name in C#?

假设我有 2 个枚举:

public enum TimeLine: short
{
    Day = 1,
    Week = 2,
    Month = 3,
    Year = 4,
}

和:

public enum TimeLine2: short
{
    Day = 2,
    Week = 1,
    Month = 3,
    Year = 4,
}

我怎样才能 map 这两个枚举,例如当我使用TimeLine.Day时,我得到“1”而不是“2”?

我们当前的解决方案是使用带有 switch 语句的 convert 方法,但随着时间的推移它变得越来越大和越来越复杂。

您可以使用Enum.TryParse<T>

public static TimeLine2? MapByName(TimeLine1 tl)
    => Enum.TryParse<TimeLine2>(tl.ToString(), out var tl2) ? tl2 : null;

这有点像“用大锤敲螺母”的情况,但您可以使用AutoMapper来完成此操作。

我不会使用AutoMapper ,除非我已经将它用于其他更困难的映射,但这里是您如何使用它。

(您需要为此添加“AutoMapper.Extensions.EnumMapping” NuGet package)

using System;
using AutoMapper;
using AutoMapper.Extensions.EnumMapping;

static class Program
{
    public enum TimeLine1 : short
    {
        Day   = 1,
        Week  = 2,
        Month = 3,
        Year  = 4,
    }

    public enum TimeLine2 : short
    {
        Day   = 2,
        Week  = 1,
        Month = 3,
        Year  = 4,
    }

    public static void Main()
    {
        var config = new MapperConfiguration(cfg => 
            cfg.CreateMap<TimeLine1, TimeLine2>()
               .ConvertUsingEnumMapping(opt => opt.MapByName()));

        var mapper = new Mapper(config);

        TimeLine1 t1 = TimeLine1.Day;
        TimeLine2 t2 = mapper.Map<TimeLine2>(t1);

        Console.WriteLine(t2); // Outputs "Day", not "Week" (which a value-based mapping would result in).
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM