簡體   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