首页 > 解决方案 > EnumFlags 到枚举值字符串列表 C#

问题描述

我正在尝试获取标志枚举值的字符串列表

我有两个枚举

enum example {
 name0 = 0,
 name1 = 1,
 name2 = 2,
 name3 = 3
}
//And a flagged enum
[Flags]
enum example2 {
 none = 0,
 name1 = 1 <<example.name1,
 name2 = 1 << example.name2,
 name3 = 1 << example.name3
}

我设置了一个标记的枚举。

example2 = name1 | name2;

我想做的是,从那个例子2 = name1 | 2;获取具有第一个枚举的整数值的字符串列表。

到目前为止,我已经尝试制作标记枚举的字符串列表:示例:

example2.toString()

//result: "name1, name2"
//I'm not quite sure how to proceed with this, I've read the documentation but can't find something helpful, probably to split and trim the string to get a list of names, then iterate over that list and somehow get the numeric value using the names
/* 
   result I'm trying to achieve:
   ["1", "2"] <-- List of strings of int values corresponding to those names.
*/

有谁知道这样做的好方法?

~这是我的第一个问题,如果解释不好,对不起。

标签: c#listenumsenum-flags

解决方案


好的,提供您告诉@Rufus L 的内容,有一个简单的解决方案

using System;
                
public class Program
{
    public static void Main()
    {
        Console.WriteLine(((int)Name.TEST).ToString());
        Console.WriteLine(((short)Name.TEST2).ToString());
        Console.WriteLine(((long)Name.TEST3).ToString());
    }

}
public enum Name
{
    TEST,
    TEST2,
    TEST3
}

的输出是 0, 1, 2 。我用不同的类型解析它,因为也许你需要一个更大的数字。

我正在编辑我的答案以防万一,因为我认为这不完全是你需要的,但它可能会派上用场,所以我留下它,我也会添加这个,如果你想将文字字符串转换为枚举值,你会需要像这样解析它

var enumVal = (Name)Enum.Parse(typeof(Name), "TEST");

然后你可以应用我之前写的


推荐阅读