如何在值共享相同名称的枚举之间进行转换?

问题描述 投票:0回答:4

如果我想在两种

Enum
类型之间进行转换,我希望其值具有相同的名称,是否有一种简洁的方法,或者我必须这样做:

enum colours_a { red, blue, green }
enum colours_b { yellow, red, blue, green }

static void Main(string[] args)
{
    colours_a a = colours_a.red;
    colours_b b;

    //b = a;
    b = (colours_b)Enum.Parse(typeof(colours_b), a.ToString());
}

c# enums
4个回答
7
投票

如果您对两个枚举有严格的控制,那么您的解决方案(或Randolpho's)就可以了。

如果你不这样做,那么我会跳过尝试变得棘手并创建一个在它们之间进行转换的静态映射类。事实上,从易于维护的角度来看,我可能会建议这样做(即使您现在按名称进行映射)。


6
投票

你也可以这么做,不知道这样是否够简洁:

enum A { One, Two }

enum B { Two, One }

static void Main(string[] args)
{
    B b = A.One.ToB();
}

这当然需要一个扩展方法:

static B ToB(this A a)
{
    switch (a)
    {
        case A.One:
            return B.One;
        case A.Two:
            return B.Two;
        default:
            throw new NotSupportedException();
    }
}

2
投票

使用这个(根据需要将变量封装到新类中):

class Program
{

    enum colours_a { red, green, blue, brown, pink }
    enum colours_b { yellow, red, blue, green }

    static int?[] map_a_to_b = null;

    static void Main(string[] args)
    {
        map_a_to_b = new int?[ Enum.GetValues(typeof(colours_a)).Length ];

        foreach (string eachA in Enum.GetNames(typeof(colours_a)))
        {

            bool existInB = Enum.GetNames(typeof(colours_b))
                            .Any(eachB => eachB == eachA);

            if (existInB)
            {
                map_a_to_b
                    [
                    (int)(colours_a)
                    Enum.Parse(typeof(colours_a), eachA.ToString())
                    ]

                    =

                    (int)(colours_b)
                    Enum.Parse(typeof(colours_b), eachA.ToString());
            }                                   
        }

        colours_a a = colours_a.red;
        colours_b b = (colours_b) map_a_to_b[(int)a];
        Console.WriteLine("Color B: {0}", b); // output red

        colours_a c = colours_a.green;
        colours_b d = (colours_b)map_a_to_b[(int)c];
        Console.WriteLine("Color D: {0}", d); // output green
        Console.ReadLine();

        colours_a e = colours_a.pink;
    // fail fast if e's color don't exist in b, cannot cast null to value type
        colours_b f = (colours_b)map_a_to_b[(int)e]; 
        Console.WriteLine("Color F: {0}", f);
        Console.ReadLine();

    }// Main
}//Program

0
投票

您可以使用扩展程序:

public static class EnumExtensions
{
    public static TTarget ConvertTo<TTarget>(this Enum sourceEnum) where TTarget : struct, Enum
    {
        if (!typeof(TTarget).IsEnum)
            throw new ArgumentException("TTarget must be an enum type.");

        if (!Enum.IsDefined(typeof(TTarget), sourceEnum.ToString()))
            throw new ArgumentException($"Invalid mapping from {sourceEnum.GetType()} to {typeof(TTarget)}.");

        string sourceName = sourceEnum.ToString();
        string targetName = Enum.GetName(typeof(TTarget), sourceEnum);

        return (TTarget)Enum.Parse(typeof(TTarget), targetName);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.