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

发布于 2024-08-30 05:54:52 字数 357 浏览 5 评论 0原文

如果我想在两个 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());
}

If I want to convert between two Enum types, the values of which, I hope, have the same names, is there a neat way, or do I have to do it like this:

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());
}

?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心如狂蝶 2024-09-06 05:54:52

如果您对两个枚举有严格的控制,那么您的解决方案(或 兰多夫的)很好。

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

If you have strict control over the two enum's, then your solution (or Randolpho's) is fine.

If you don't, then I'd skip trying to be tricky and create a static mapping class that converts between them. In fact, I'd probably recommend that anyway (even if you map by name there for now), from an ease-of-maintenance perspective.

柠檬色的秋千 2024-09-06 05:54:52

你也可以这样做,不知道它是否足够整洁:

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();
    }
}

You can also do this, don't know if it's neat enough:

enum A { One, Two }

enum B { Two, One }

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

This of course requires an extension method:

static B ToB(this A a)
{
    switch (a)
    {
        case A.One:
            return B.One;
        case A.Two:
            return B.Two;
        default:
            throw new NotSupportedException();
    }
}
你如我软肋 2024-09-06 05:54:52

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

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

Use this (encapsulate variables to new class as needed):

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
背叛残局 2024-09-06 05:54:52

您可以使用扩展:

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);
    }
}

you can use Extensions:

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(
quot;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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文